如何将.aspx页面添加到现有的MVC 4项目中?

Shu*_*mov 12 asp.net asp.net-mvc webforms razor asp.net-mvc-4

我有ASP.NET MVC 4项目.我想向这个MVC项目添加.aspx另外两个WebForms项目的页面.我有几个问题:

  1. 我应该在哪里复制这些.aspx文件,我应该如何配置我的路线?
  2. 我该如何将这些.aspx页面~/Shared/_Layout.chtml用作母版?
  3. 此外,此.aspx页面使用.ascx控件.我应该在哪里存放它们?
  4. 我该如何修改web.config文件?

我查看了这个问题中发布的链接,但它们似乎已经过时了.很多链接解释了如何将MVC添加到WebForms,但我一直在寻找.

任何有用的链接将不胜感激.谢谢!

Shu*_*mov 17

解决方案:

事实证明,将.aspx页面添加到现有的MVC项目比将mvc添加到.aspx更容易.对我来说最有趣的事情是发现一个项目范围内的webforms和MVC 在IIS上共享一个运行时.

所以我做了什么:

  1. 将另一个项目的.aspx页面添加到我的MVC项目的根目录
  2. 为我的webforms页面创建了新的母版页(右键单击项目 - > add-> new item-> Master Page)
  3. 为了使WF的Master Page和MVC的_Layout.chtml共享同一个Master'View ',我发现这篇很棒的文章允许你在.aspx页面中调用类似于@ Html.RenderPartial()方法的东西
  4. 以下代码提供了有关如何在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)
  5. 由于我只在所有页面中共享"菜单",因此我将其添加到部分视图中,然后在_Layout.chtml中调用它

    @Html.Partial("_Menu")
    
    Run Code Online (Sandbox Code Playgroud)

MasterPage.Master中像这样:

    <% WebFormMVCUtil.RenderPartial("_Menu", null ); %>
Run Code Online (Sandbox Code Playgroud)

这就是它的全部.因此,我的_Layout.chtmlMasterPage.Master使用相同的共享部分视图.我只需浏览它们即可访问.aspx页面.如果您对路由系统有一些问题,可以routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");在App_Start中添加到routeConfig.

我使用的来源:

  1. 将asp net mvc与webforms结合使用
  2. 混合Web窗体和ASP.NET MVC
  3. MixingRazorViewsAndWebFormsMasterPages
  4. 如何在webform中包含局部视图

我希望以后可以帮助别人.

  • 我在网络表单的调用中被困在 GetModel() 上。我看到的错误是“z.aspx 不包含 'GetModel' 的定义,并且找不到接受类型 'z_aspx' 第一个参数的扩展方法(您是否缺少 using 指令或程序集引用?)我可以' t 找到 GetModel 的定义位置。 (2认同)