更新时间:2023-02-16 23:41:44
解决方案:
事实证明,向现有的 MVC 项目添加 .aspx 页面比将mvc添加到.aspx更加容易.对我而言,最有趣的事情是发现在一个项目范围内,webforms和MVC在IIS上共享一个运行时.
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.
那我做了什么:
以下代码提供了有关如何在WebForms中实现 RenderPartial 方法的信息:
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 );
}
}
将其添加到.aspx页的codebehind.cs.然后,您可以从网络表单中调用它,如下所示:
Add it to codebehind.cs of your .aspx page. Then you can call it from the webforms like this:
<% WebFormMVCUtil.RenderPartial( "ViewName", this.GetModel() ); %>
由于我所有页面之间仅共享菜单",因此将其添加到部分视图中,然后在 _Layout.chtml
@Html.Partial("_Menu")
并在 MasterPage.Master 中像这样:
<% WebFormMVCUtil.RenderPartial("_Menu", null ); %>
仅此而已.结果,我的 _Layout.chtml 和 MasterPage.Master 使用了相同的共享局部视图.而且,我可以通过在 .aspx 页面上导航来访问它们.如果路由系统遇到问题,可以在App_Start中将routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
添加到routeConfig中.
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.
我使用的来源:
我希望以后会有所帮助.
I hope it will help somebody later on.