将共享局部视图渲染为字符串时出错

时间:2015-04-26 16:01:43

标签: c# asp.net-mvc-5

我正在使用此代码,我发现将部分视图呈现为字符串。

    public string RenderPartialViewToString(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();
    }

我正在喂这样的功能:

var s = RenderPartialViewToString("~/Views/Shared/_MyPartialView.cshtml", MyModel);

但是我收到以下错误:

Type 'ASP._Page_Views_Shared__MyPartialView_cshtml' does not inherit from 'System.Web.UI.UserControl'.

任何人都知道我如何修复此错误?

1 个答案:

答案 0 :(得分:0)

ViewPage适用于Web窗体视图,不适用于Razor视图。

我想您可能对RazorEngine项目感兴趣:http://antaris.github.io/RazorEngine/