部分视图到字符串

时间:2013-03-22 09:20:07

标签: c# html asp.net-mvc

我想要使用PartialView呈现的HTML代码。例如

var partView = PartialView("myView", myModel);
string content =??;

我应该放什么而不是问号?

1 个答案:

答案 0 :(得分:1)

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();
    }
string content = RenderPartialToString("myView", myModel);