Asp.net

如何將 .aspx 頁面添加到現有的 MVC 4 項目?

  • August 25, 2014

我有工作 ASP.NET MVC 4 項目。我想向這個 MVC 項目添加.aspx另一個 WebForms 項目的 2 頁。我有幾個問題:

  1. 我應該在哪裡複製這些.aspx文件,我應該如何配置我的路線?
  2. 我應該如何告訴這個.aspx頁面~/Shared/_Layout.chtml用作母版頁?
  3. 此外,此*.aspx 頁面使用.ascx 控制項*。我應該把它們存放在哪裡?
  4. 我應該如何修改web.config 文件?

我查看了這個問題中發布的連結,但它們似乎已經過時了。很多連結都解釋瞭如何將 MVC 添加到 WebForms,但我一直在尋找。

任何有用的連結將不勝感激。謝謝!

解決方案:

事實證明,將**.aspx頁面添加到現有MVC項目比將 mvc 添加到 .aspx 更容易完成。對我來說最有趣的事情是發現 webforms 和 MVC 在一個項目的範圍內共享一個**IIS 上的執行時。

所以我做了什麼:

  1. 將另一個項目中的.aspx頁面添加到我的MVC項目的根目錄
  2. 為我的網路表單頁面創建了新的母版頁(右鍵點擊項目->添加->新項目->母版頁)
  3. 為了使WF的母版頁和 MVC 的****_Layout.chtml共享相同的主“視圖”,我發現這篇很棒的文章允許您在.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 );
   }

}

將其添加到 .aspx 頁面的 codebehind.cs。然後你可以像這樣從網路表單中呼叫它:

<% WebFormMVCUtil.RenderPartial( "ViewName", this.GetModel() ); %>
  1. 因為我只有在所有頁面之間共享“菜單”,所以我將它添加到部分視圖中,然後在**_Layout.chtml中呼叫它**
@Html.Partial("_Menu")

MasterPage.Master中是這樣的:

   <% WebFormMVCUtil.RenderPartial("_Menu", null ); %>

這就是它的全部。因此,我的**_Layout.chtmlMasterPage.Master使用相同的共享局部視圖。我可以通過導航訪問.aspx**頁面。如果您對路由系統有一些問題,您可以在 App_Start 中添加routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");到您的 routeConfig。

我使用的來源:

  1. 將 asp net mvc 與 webforms 結合使用
  2. 混合 Web 窗體和 ASP.NET MVC
  3. 混合 RazorViews 和 WebFormsMasterPages
  4. 如何在 web 表單中包含部分視圖

我希望它會在以後對某人有所幫助。

引用自:https://stackoverflow.com/questions/25385532