在 MVC3 Razor 中,如何在操作中获取渲染视图的 html? [英] In MVC3 Razor, how do I get the html of a rendered view inside an action?

查看:25
本文介绍了在 MVC3 Razor 中,如何在操作中获取渲染视图的 html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does anybody know how to get the generated html of a view inside an action?

是不是这样:

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

推荐答案

我在名为 Utilities.Common 的类中使用静态方法我不断将视图作为 JSON 对象的属性传递回客户端所以我需要将它们呈现为字符串.给你:

I use a static method in a class I called Utilities.Common I pass views back to the client as properties of JSON objects constantly so I had a need to render them to a string. Here ya go:

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.

This will work for full views as well as partial views, just change ViewEngines.Engines.FindPartialView to ViewEngines.Engines.FindView.

这篇关于在 MVC3 Razor 中,如何在操作中获取渲染视图的 html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆