Skip to content

Instantly share code, notes, and snippets.

@abjerner
Created December 15, 2017 08:34
Show Gist options
  • Save abjerner/47c9a0d49e866ae621f8c674d9a2fd37 to your computer and use it in GitHub Desktop.
Save abjerner/47c9a0d49e866ae621f8c674d9a2fd37 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MyWebsite {
public partial class Utils {
public static class Mvc {
public class WebFormController : Controller { }
public static HtmlString RenderPartial(string partialName, object model) {
// Get a wrapper for the legacy WebForm context
HttpContextWrapper context = new HttpContextWrapper(HttpContext.Current);
// Create a mock route that points to the empty controller
RouteData route = new RouteData();
route.Values.Add("controller", "WebFormController");
// Create a controller context for the route and http context
ControllerContext ctx = new ControllerContext(new RequestContext(context, route), new WebFormController());
if (partialName.StartsWith("Partials/")) partialName = "~/Views/" + partialName;
if (!partialName.EndsWith(".cshtml")) partialName += ".cshtml";
// Find the partial view using the view engine
ViewEngineResult result = ViewEngines.Engines.FindPartialView(ctx, partialName);
if (result == null || result.View == null) throw new Exception("Partial view \"" + partialName + "\" not found.");
// Render the partial view to a StringBuilder
StringBuilder sb = new StringBuilder();
using (StringWriter writer = new StringWriter(sb)) {
// Create a view context and assign the model
ViewContext vctx = new ViewContext(ctx, result.View, new ViewDataDictionary { Model = model }, new TempDataDictionary(), writer);
// Render the partial view
result.View.Render(vctx, writer);
}
return new HtmlString(sb.ToString());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment