尝试将视图呈现为字符串以用作电子邮件模板。我目前正在尝试实施此示例: https://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String
但是我对这部分代码有困难:
public ViewRenderer(ControllerContext controllerContext = null)
{
// Create a known controller from HttpContext if no context is passed
if (controllerContext == null)
{
if (HttpContext.Current != null)
controllerContext = CreateController<ErrorController>().ControllerContext;
else
throw new InvalidOperationException(
"ViewRenderer must run in the context of an ASP.NET " +
"Application and requires HttpContext.Current to be present.");
}
Context = controllerContext;
}
Visual Studio给出了以下错误:
“无法找到类型或命名空间名称'ErrorController'(您是否缺少using指令或程序集引用?)”
我可能错过了一些明显的东西,却看不出它是什么。有什么想法吗?
答案 0 :(得分:6)
如果您需要将视图渲染为字符串,这里是我编写的控制器的扩展方法。
注意:我会尝试找到我用来帮助我的确切链接,并在找到时更新我的答案。
Here是另一个链接,描述了这种方法。
这应该可以解决问题:
public static string RenderViewToString(this Controller controller, string viewName, object model)
{
var context = controller.ControllerContext;
if (string.IsNullOrEmpty(viewName))
viewName = context.RouteData.GetRequiredString("action");
var viewData = new ViewDataDictionary(model);
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
如果您想从控制器中调用它,只需执行以下操作:
var strView = this.RenderViewToString("YourViewName", yourModel);