在MVC3 Razor中,如何在一个动作中获得渲染视图的html?

有没有人知道如何获得一个行动内的视图生成的HTML?

是这样的:

public ActionResult Do() { var html = RenderView("hello", model); ... } 

我在一个名为Utilities.Common的类中使用静态方法,我将视图作为JSON对象的属性持续传递给客户端,所以我需要将它们呈现为string。 这里你去:

 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

上面的@Chev接受的答案是好的,但我想呈现一个具体行动的结果,而不仅仅是一个特定的观点

另外,我需要能够将parameter passing给该动作,而不是dependency injection模型。

所以我想出了我自己的方法,我把我的控制器的基类(提供给他们所有):

  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的结果,我可以通过调用Foo方法来获取ViewResult ,然后调用RenderViewResultAsString来获取HTML文本:

  var viewResult = this.Foo(model, bar); var html = this.RenderViewResultAsString(viewResult);