[英]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.