C# – ASP.NET MVC Razor:如何在控制器动作中渲染Razor Partial View的HTML

如何在ASP.NET视图引擎is known上生成给定部分视图的HTML。

但如果这个功能在剃刀部分视图上使用,它不工作,因为异常说部分视图不是从“UserControl”派生。

如何修复渲染以支持剃刀局部视图?

我需要这是因为我从这个部分视图生成电子邮件…

更新:

失败的代码(@mcl):

public string RenderPartialToString(string controlName, object viewData)
    {
        ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };
        viewPage.Url = this.GetUrlHelper();

        string fullControlName = "~/Views/Email/" + controlName + ".ascx";

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

        StringBuilder sb = new StringBuilder();
        using (StringWriter sw = new StringWriter(sb))
        {
            using (HtmlTextWriter tw = new HtmlTextWriter(sw))
            {
                viewPage.RenderControl(tw);
            }
        }
        return sb.ToString();
    }
@Html.Partial("nameOfPartial", Model)

更新

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

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

        return sw.GetStringBuilder().ToString();
    }
}
http://stackoverflow.com/questions/4344533/asp-net-mvc-razor-how-to-render-a-razor-partial-views-html-inside-the-controll

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:C# – ASP.NET MVC Razor:如何在控制器动作中渲染Razor Partial View的HTML