ASP.NET MVC: Including Partial MVC Views in ASP.NET Form Pages

We have old ASP.NET Forms pages and new MVC views and partial views in the same solution. Some pages on the site are MVC, and outdated pages are forms.

One of these legacy form pages is the .ascx control. Is there a way for me to add a partial MVC view (.ascx) to this Forms.ascx control?

+4
source share
3 answers

I use this method to embed partial MVC data in web form pages. Not sure if it works in the webforms user element, but that should be possible.

Step 1. In the MVC part of your application, create the following helper function. This does all the hard work:

namespace MvcApplication { // create a dummy controller public class DummyController : Controller { } public static class MvcPartialHelper { public static void RenderPartial(string partialViewName, object model) { ControllerContext controllerContext; HttpContextBase httpContextBase; IView view; RouteData routeData; ViewContext viewContext; httpContextBase = new HttpContextWrapper(HttpContext.Current); routeData = new RouteData(); routeData.Values.Add("controller", typeof(DummyController).Name); controllerContext = new ControllerContext(new RequestContext(httpContextBase, routeData), new DummyController()); view = ViewEngines.Engines.FindPartialView(controllerContext, partialViewName).View; viewContext = new ViewContext(controllerContext, view, new ViewDataDictionary { Model = model }, new TempDataDictionary(), httpContextBase.Response.Output); view.Render(viewContext, httpContextBase.Response.Output); } } } 

then on your web page (or user control):

add the following to refer to the above:

 <%@ Import Namespace="MvcApplication" %> 

and then when you need to display partial, you can add something like:

 <% MvcPartialHelper.RenderPartial("~/views/shared/TestPartial.ascx", "hello - this is my model"); %> 

where the second parameter is your "Model".

I use this technique extensively in a mixed MVC / Webforms environment and it works like a dream!

Enjoy

+2
source

No, no, since you do not have the Html helper needed to complete this insert:

 <%= Html.RenderPartial("foo") %> 

Also, your partial MVC code is strongly typed (not like that) and you will not have access to the model.

Also, when you port your legacy webforms application to ASP.NET MVC, it should be the other way around.

0
source

Technically, this is possible, although you need to jump over a few hoops to achieve what you ask. You need to create a dummy controller context, view the Context and the associated environment, and then create a property on your page behind the code to simulate the model.

Let me know if you want detailed instructions / example

0
source

All Articles