在ASP.NET中将完整视图渲染为字符串

时间:2014-06-10 14:02:32

标签: asp.net asp.net-mvc

我发现此代码将部分视图呈现为字符串:

public static string RenderPartialToString(string controlName, object viewData)
    {
        ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };

        viewPage.ViewData = new ViewDataDictionary(viewData);
        viewPage.Controls.Add(viewPage.LoadControl(controlName));

        StringBuilder sb = new StringBuilder();
        using (StringWriter sw = new StringWriter(sb))
        {
            using (HtmlTextWriter tw = new HtmlTextWriter(sw))
            {
                viewPage.RenderControl(tw);
            }
        }

        return sb.ToString();
    }

但是我需要将完整视图呈现为字符串(包含ViewData)。

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

将完整视图呈现为字符串:

    private string RenderViewToString(string viewName, object model=null)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        if (model != null)
            ViewData.Model = model;

        // you can pass in additional arguments to this function 
        // and manipulate the ViewData further if you need to

        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

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

如果您想要在不使用模型

的情况下呈现页面,请按此使用
var text = RenderViewToString("Index");

并且像这样,如果您想使用模型

呈现页面
var text = RenderViewToString("OtherPage", model);