Skip to content

Instantly share code, notes, and snippets.

@Boggin
Forked from SimonRice/RenderActionPartial.spark
Created October 25, 2012 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Boggin/3951330 to your computer and use it in GitHub Desktop.
Save Boggin/3951330 to your computer and use it in GitHub Desktop.
Utility class to render MVC Partials & Actions in WebForms (or server side controls).
<% WebFormMvcUtil.Html.RenderAction("Index", "PhoneNumber"); %>
namespace Website
{
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
public class WebFormMvcUtil
{
private static HtmlHelper html;
public static HtmlHelper Html
{
get
{
return html ?? (html = new HtmlHelper(CreateViewContext(), new ViewUserControl()));
}
}
public static ViewContext CreateViewContext()
{
// get a wrapper for the legacy WebForm context
var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
// create a mock route that points to the empty controller
var routeData = new RouteData();
routeData.Values.Add("controller", "WebFormController");
// create a controller context for the route and http context
var controllerContext =
new ControllerContext(
new RequestContext(httpContextWrapper, routeData),
new WebFormController());
// find the partial view using the viewengine
IView view =
ViewEngines
.Engines
.FindPartialView(controllerContext, "RenderActionPartial")
.View;
// create a view context and assign the model
var viewContext =
new ViewContext(
controllerContext,
view,
new ViewDataDictionary(),
new TempDataDictionary(),
HttpContext.Current.Response.Output);
return viewContext;
}
}
internal class WebFormController : Controller
{
}
}
@Boggin
Copy link
Author

Boggin commented Oct 25, 2012

Small layout changes to accommodate standard StyleCop rules.

@Boggin
Copy link
Author

Boggin commented Oct 26, 2012

I can't use the RenderPartial but I can get my content if I create a new HtmlHelper.

@Boggin
Copy link
Author

Boggin commented Oct 26, 2012

Simpler and clearer and works with MVC 3

@Boggin
Copy link
Author

Boggin commented Oct 26, 2012

Idea to create HtmlHelper came from http://stackoverflow.com/a/4247959/444244

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment