[英]Rendering a partial view from viewbag in c# mvc 3
我有一个包含两个项目的解决方案,并且试图将一个项目的局部视图发送到另一个项目。
所以在项目AI中有一个像这样的控制器:
public PartialViewResult Index()
{
return PartialView("_Forms");
}
在项目BI中有一个像这样的控制器:
public ActionResult Index()
{
var form = pa.Index(); // <-- This is the controller from controller A
ViewBag.CMSForm = form;
return View();
}
...到目前为止还不错,但是现在我需要从ViewBag.CMSForm渲染部分视图,而我不知道该如何做。
如果您仅尝试渲染局部视图...
我只是在搞弄类似的东西,我需要根据用户从哪里路由,在一个Index视图上呈现不同的局部视图。
我所做的就是这样...
public ActionResult Index()
{
ViewBag.CMSForm = "_Forms";
return View();
}
然后在您看来
@{
string form= ViewBag.CMSForm;
}
@section CustomForm{
@Html.Partial(form)
}
我已根据您的情况从http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/修改了该解决方案。
将您的代码从项目B更改为此:
public ActionResult Index()
{
var form = pa.Index(); // <-- This is the controller from controller A
using (var sw = new StringWriter())
{
// Find the actual partial view.
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, form.ViewName);
// Build a view context.
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
// Render the view.
viewResult.View.Render(viewContext, sw);
// Get the string rendered.
ViewBag.CMSForm = sw.GetStringBuilder().ToString();
}
return View();
}
为什么不鉴于ControllerB使用ControllerA.Index-action的呈现?
<p>
@Html.Action("Index", "ControllerA")
</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.