开发者

Call ASP.NET MVC3 Area From WebForms

We are in the process of migrating a large ASP.NET WebForms application to ASP.NET MVC3 and have hit a small snag that hopefully someone can help us with.

We have a small subset of开发者_如何学运维 the site that will for the time-being have to remain as a WebForms implementation until we can migrate it to MVC3, which is fine and we have sucessfully hybridized the site to achieve this.

However, we need to be able to replace some of the existing UserControl implementations that we have on the WebForms pages with content that should now be generated via a new MVC3 Areas implementation - is there any way to execute an MVC3 Area from within a classic WebForms page?


Ok; the answer seems to be to make a Partial View that calls the required Area using the standard Html.Action extension method:

@Html.Action("Index", "Home", new { Area = "HelloWorld" })

A dummy Controller is required:

public class WebFormController : Controller { }

We can then get a ControllerContext using our dummy and from there we can get the Partial View and render it:

public class WebFormMvcUtil
{
    public static string RenderPartial(string partialName, object model)
    {
        var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);

        var routeData = new RouteData();
        routeData.Values.Add("controller", "WebFormController");

        var controllerContext = new ControllerContext(new RequestContext(httpContextWrapper, routeData),
                                                      new WebFormController());

        IView view = ViewEngines.Engines.FindPartialView(controllerContext, partialName).View;

        ViewContext viewContext;
        var stringBuilder = new StringBuilder();
        using (var stringWriter = new StringWriter(stringBuilder))
        {
            viewContext = new ViewContext(controllerContext, view, new ViewDataDictionary {Model = model}, new TempDataDictionary(), stringWriter);
            view.Render(viewContext, viewContext.Writer);
        }

        return stringBuilder.ToString();
    }
}

This boils down to being able to place a simple

<%= WebFormMvcUtil.RenderPartial("_Area", null) %>

in a WebForms page and the required Area will render.


You could create a server control that calls the MVC-3 route to receive the HTML to be displayed. The Server Control just renders the received HTML code. Derive from WebControl and override the Render methods. A sample for a server control you can finde here.

To get the code from the MVC-3 you could use the WebRequest object, something like this:

WebRequest request = WebRequest.Create ("http://www.mypage.com/mvcroute");
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Stream dataStream = response.GetResponseStream ();
using (StreamReader reader = new StreamReader (dataStream))
{
    string responseFromServer = reader.ReadToEnd ();
    // render response to output
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜