如何在Asp.Net MVC中动态插入部分视图

我正在将Webforms站点迁移到MVC。 在我的webforms网站中,我有使用各种用户控件组合的页面,然后是html块,然后是标签,文本框等。

我不想硬连线每个页面,所以我将从CMS驱动每个页面的输出,指定将控件插入页面的顺序。

我想每个控件现在都是MVC中的部分视图。 (如果这不正确,请告诉我)。

因此,如果我有两个不同的局部视图,ViewA和ViewB,如何创建一个控制器方法,将部分视图插入到按CMS确定的给定URL的顺序返回的视图中?

因此,假设控制器方法称为Reports,它采用名为product的参数。

例如// MySite / Reports?product = A返回包含ViewA,ViewA,ViewB,ViewA的视图

// MySite / Reports?product = B返回包含ViewA,ViewB,ViewA,ViewB等的视图

那么代码应该用于控制器方法呢?

我希望这是有道理的

如果我理解正确,这应该可以解决你的问题

只需创建一个派生自PartialViewResult的新类,它接受多个视图名称来呈现它们。 为了使它更有用,为控制器创建一个新的扩展方法来调用自定义的ViewResult。

这对我有用。 你可以这么简单地使用它:

public ActionResult Index() { return this.ArrayView(new string[] { "ViewA", "ViewB" }); } 

要使它工作,ArrayViewResult类应该是:

 public class ArrayViewResult : PartialViewResult { public IEnumerable Views; protected override ViewEngineResult FindView(ControllerContext context) { return base.FindView(context); } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if (!Views.Any()) throw new Exception("no view..."); TextWriter writer = context.HttpContext.Response.Output; foreach(var view in Views) { this.ViewName = view; ViewEngineResult result = FindView(context); ViewContext viewContext = new ViewContext(context, result.View, ViewData, TempData, writer); result.View.Render(viewContext, writer); result.ViewEngine.ReleaseView(context, result.View); } } } 

扩展方法:

 namespace System.Web.Mvc { public static class ArrayViewResultExtension { public static ArrayViewResult ArrayView(this Controller controller, string[] views) { return ArrayView(controller, views, null); } public static ArrayViewResult ArrayView(this Controller controller, string[] views, object model) { if (model != null) { controller.ViewData.Model = model; } return new ArrayViewResult { ViewName = "", ViewData = controller.ViewData, TempData = controller.TempData, ViewEngineCollection = controller.ViewEngineCollection, Views = views }; } } }