且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将视图渲染为字符串

更新时间:2023-02-25 08:16:10

如果您需要将视图呈现为字符串,这是我编写的控制器的扩展方法.

If you need to Render your view as a string, here is an extension method for the controller I wrote.

注意:我将尝试找到用于帮助我的确切链接,并在找到答案时更新我的​​答案.

此处是描述此方法的另一个链接.

Here is another link, describing this method.

这应该可以解决问题:

public static string RenderViewToString(this Controller controller, string viewName, object model)
    {
        var context = controller.ControllerContext;
        if (string.IsNullOrEmpty(viewName))
            viewName = context.RouteData.GetRequiredString("action");

        var viewData = new ViewDataDictionary(model);

        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
            var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }

如果要从控制器调用它,只需执行以下操作:

If you want to call this from a controller, you simply do the following:

var strView = this.RenderViewToString("YourViewName", yourModel);