Shu*_*mov 12 asp.net asp.net-mvc webforms razor asp.net-mvc-4
我有ASP.NET MVC 4项目.我想向这个MVC项目添加.aspx另外两个WebForms项目的页面.我有几个问题:
.aspx文件,我应该如何配置我的路线?.aspx页面~/Shared/_Layout.chtml用作母版?我查看了这个问题中发布的链接,但它们似乎已经过时了.很多链接解释了如何将MVC添加到WebForms,但我一直在寻找.
任何有用的链接将不胜感激.谢谢!
Shu*_*mov 17
解决方案:
事实证明,将.aspx页面添加到现有的MVC项目比将mvc添加到.aspx更容易.对我来说最有趣的事情是发现一个项目范围内的webforms和MVC 在IIS上共享一个运行时.
所以我做了什么:
以下代码提供了有关如何在WebForms中实现RenderPartial方法的信息:
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
将它添加到.aspx页面的codebehind.cs.然后你可以从webforms中调用它,如下所示:
<% WebFormMVCUtil.RenderPartial( "ViewName", this.GetModel() ); %>
Run Code Online (Sandbox Code Playgroud)由于我只在所有页面中共享"菜单",因此我将其添加到部分视图中,然后在_Layout.chtml中调用它
@Html.Partial("_Menu")
Run Code Online (Sandbox Code Playgroud)在MasterPage.Master中像这样:
<% WebFormMVCUtil.RenderPartial("_Menu", null ); %>
Run Code Online (Sandbox Code Playgroud)
这就是它的全部.因此,我的_Layout.chtml和MasterPage.Master使用相同的共享部分视图.我只需浏览它们即可访问.aspx页面.如果您对路由系统有一些问题,可以routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");在App_Start中添加到routeConfig.
我使用的来源:
我希望以后可以帮助别人.