I have working ASP.NET MVC 4 project. I want to add to this MVC project 2 .aspx
pages of another WebForms project. I have several questions:
.aspx
files and how should I config my
routes? .aspx
pages to use ~/Shared/_Layout.chtml
as a master page?
I have looked at the links posted in this question, but they seemed to be outdated. A lot of the links explain how to add MVC to WebForms, but I am looking for all the way around.
Any useful links would be appreciated. Thanks!
The solution:
As it turned out, adding .aspx pages to the existing MVC project is an even easier task to accomplish than adding mvc to .aspx. The most interesting thing for me was to find out that both webforms and MVC, in the scope of one project share one runtime on IIS.
So what I did:
The following code provides information how to implement RenderPartial method in WebForms:
public class WebFormController : Controller { }
public static class WebFormMVCUtil
{
public static void RenderPartial( string partialName, object model )
{
//get a wrapper for the legacy WebForm context
var httpCtx = new HttpContextWrapper( System.Web.HttpContext.Current );
//create a mock route that points to the empty controller
var rt = new RouteData();
rt.Values.Add( "controller", "WebFormController" );
//create a controller context for the route and http context
var ctx = new ControllerContext(
new RequestContext( httpCtx, rt ), new WebFormController() );
//find the partial view using the viewengine
var view = ViewEngines.Engines.FindPartialView( ctx, partialName ).View;
//create a view context and assign the model
var vctx = new ViewContext( ctx, view,
new ViewDataDictionary { Model = model },
new TempDataDictionary() );
//render the partial view
view.Render( vctx, System.Web.HttpContext.Current.Response.Output );
}
}
Add it to codebehind.cs of your .aspx page. Then you can call it from the webforms like this:
<% WebFormMVCUtil.RenderPartial( "ViewName", this.GetModel() ); %>
Since I had only the 'menu' shared among all my pages, I added it to the partial View, then called it in _Layout.chtml
@Html.Partial("_Menu")
and in MasterPage.Master like this:
<% WebFormMVCUtil.RenderPartial("_Menu", null ); %>
That is all there is to it. As a result my _Layout.chtml and MasterPage.Master use the same shared partial views. And I can acess .aspx pages simply by navigating on them. If you have some issues with routing system, you can add routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
to your routeConfig in App_Start.
Sources I used:
I hope it will help somebody later on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With