asp.NET MVC4在部分视图中使用部分视图

时间:2021-04-25 03:38:10

Let's assume I have 3 custom controllers: AController, BController and CControler and one default HomeController. Each of the first three controllers have a very unique partial view for them, let's name them APartial, BPartial, CPartial and these are invoked with AFunction, BFunction and CFunction with a template looking like:

假设我有3个自定义控制器:AController,BController和CControler以及一个默认的HomeController。前三个控制器中的每一个都有一个非常独特的局部视图,我们将它们命名为APartial,BPartial,CPartial,并使用AFunction,BFunction和CFunction调用这些模板,其模板如下所示:

public ActionResult XFunction
{
    /*put some data into a ViewBag*/
    return PartialView("XPartial");
}

Respectivelly, APartial.cshtml, BPartial.cshtml, CPartial.cshtml are in the Shared folder. What is the best way to return all three views in one page when HomeController's Index (ActionResult method) is called. I tried rendering each like:

APartial.cshtml,BPartial.cshtml,CPartial.cshtml分别位于Shared文件夹中。调用HomeController的Index(ActionResult方法)时,在一个页面中返回所有三个视图的最佳方法是什么。我尝试渲染每个像:

using (StringWriter sw = new StringWriter())
{
    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "XFunction");
    ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);

    return MvcHtmlString.Create(sw.GetStringBuilder().ToString());
}

then putting each into ViewBag's dynamic variables, but I have a feeling there has to be a way nicer solution.

然后把每个放入ViewBag的动态变量,但我觉得必须有一个更好的解决方案。

1 个解决方案

#1


1  

Use RenderAction in your view. Good explanation is here: http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/

在视图中使用RenderAction。这里有很好的解释:http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/

#1


1  

Use RenderAction in your view. Good explanation is here: http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/

在视图中使用RenderAction。这里有很好的解释:http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/