C# 在c mvc 3中从viewbag渲染局部视图
我有一个包含两个项目的解决方案,我正在尝试将部分视图从一个项目发送到另一个项目 因此,在项目A中,我有一个如下控制器:C# 在c mvc 3中从viewbag渲染局部视图,c#,asp.net-mvc,asp.net-mvc-3,C#,Asp.net Mvc,Asp.net Mvc 3,我有一个包含两个项目的解决方案,我正在尝试将部分视图从一个项目发送到另一个项目 因此,在项目A中,我有一个如下控制器: public PartialViewResult Index() { return PartialView("_Forms"); } public ActionResult Index() { var form = pa.Index(); // <-- This is the controller
public PartialViewResult Index()
{
return PartialView("_Forms");
}
public ActionResult Index()
{
var form = pa.Index(); // <-- This is the controller from controller A
ViewBag.CMSForm = form;
return View();
}
在项目B中,我有这样一个控制器:
public PartialViewResult Index()
{
return PartialView("_Forms");
}
public ActionResult Index()
{
var form = pa.Index(); // <-- This is the controller from controller A
ViewBag.CMSForm = form;
return View();
}
。。。到目前为止还不错,但现在我需要从ViewBag.CMSForm渲染部分视图,我不知道如何进行渲染。我已经根据您的案例调整了解决方案 将您的代码从项目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>
如果仅尝试渲染局部视图 我只是搞乱了一些类似的东西,我需要根据用户路由的位置在一个索引视图上呈现不同的部分视图 我所做的是这样的
public ActionResult Index()
{
ViewBag.CMSForm = "_Forms";
return View();
}
那么在你看来
@{
string form= ViewBag.CMSForm;
}
@section CustomForm{
@Html.Partial(form)
}
这帮助我更接近我的目标,但我遇到了一个新问题。我需要在项目B中保留我的局部视图,当我尝试将它们呈现为项目a中的字符串时,它使用a的controllercontext。这意味着它只在A中查找分部。当我调试B并尝试将视图呈现为字符串时,一切正常。