有人知道如何在动作中获取生成的视图html吗?
是这样的:
public ActionResult Do()
{
var html = RenderView("hello", model);
...
}
答案 0 :(得分:152)
我在一个名为Utilities.Common
的类中使用静态方法我将视图作为JSON对象的属性不断传递回客户端,因此我需要将它们渲染为字符串。你走了:
public static string RenderPartialViewToString(Controller controller, string viewName, object model)
{
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.ToString();
}
}
这适用于完整视图和部分视图,只需将ViewEngines.Engines.FindPartialView
更改为ViewEngines.Engines.FindView
。
答案 1 :(得分:4)
以上@Chev接受的答案很好,但我想渲染特定操作的结果,而不仅仅是特定的视图。
此外,我需要能够将参数传递给该操作,而不是依赖于注入模型。
所以我想出了我自己的方法,我把它放在我的控制器的基类中(让它们全部可用):
protected string RenderViewResultAsString(ViewResult viewResult)
{
using (var stringWriter = new StringWriter())
{
this.RenderViewResult(viewResult, stringWriter);
return stringWriter.ToString();
}
}
protected void RenderViewResult(ViewResult viewResult, TextWriter textWriter)
{
var viewEngineResult = this.ViewEngineCollection.FindView(
this.ControllerContext,
viewResult.ViewName,
viewResult.MasterName);
var view = viewEngineResult.View;
try
{
var viewContext = new ViewContext(
this.ControllerContext,
view,
this.ViewData,
this.TempData,
textWriter);
view.Render(viewContext, textWriter);
}
finally
{
viewEngineResult.ViewEngine.ReleaseView(this.ControllerContext, view);
}
}
假设我有一个名为Foo
的动作,它接受一个模型对象和一些其他参数,它们共同影响将使用的视图:
public ViewResult Foo(MyModel model, int bar)
{
if (bar == 1)
return this.View("Bar1");
else
return this.View("Bar2", model);
}
现在,如果我想获得调用操作Foo
的结果,我可以通过调用ViewResult
方法获取Foo
,然后调用RenderViewResultAsString
获取HTML文本:
var viewResult = this.Foo(model, bar);
var html = this.RenderViewResultAsString(viewResult);