在MVC3Razor中,如何在操作中获取呈现视图的html?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (25)

有人知道如何在操作中获取视图的生成html吗?

是这样吗?

public ActionResult Do()
{
    var html = RenderView("hello", model);
...
}
提问于
用户回答回答于

在我调用的类中使用静态方法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.FindPartialViewViewEngines.Engines.FindView即可。

用户回答回答于

我想出了自己的方法,将控制器的基类放入其中(将其提供给所有控制器):

    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);

扫码关注云+社区