小编典典

ASP.NET MVC Razor:如何在控制器动作中呈现Razor局部视图的HTML

c#

如何在ASP.NET视图引擎上生成给定局部视图的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();
    }

阅读 316

收藏
2020-05-19

共1个答案

小编典典

@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();
    }
}
2020-05-19