gpt4 book ai didi

c# - ASP.NET MVC Razor : How to render a Razor Partial View's HTML inside the controller action

转载 作者:IT王子 更新时间:2023-10-29 03:36:05 24 4
gpt4 key购买 nike

如何在 ASP.NET View 引擎上生成给定局部 View 的 HTML is known .

但如果此功能用于 Razor 部分 View ,则它不起作用,因为异常(exception)情况表明部分 View 不是从“UserControl”派生的。

如何修复渲染以支持 Razor 局部 View ?

我需要这个,因为我从这个部分 View 生成电子邮件......

更新:

失败的代码(@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();
}
}

关于c# - ASP.NET MVC Razor : How to render a Razor Partial View's HTML inside the controller action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4344533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com