我试图将视图呈现为字符串以用作电子邮件模板.我目前正在尝试实施此示例: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;
}
Run Code Online (Sandbox Code Playgroud)
Visual Studio给出了以下错误:
"无法找到类型或命名空间名称'ErrorController'(您是否缺少using指令或程序集引用?)"
我可能错过了一些明显但却看不清楚的东西.有任何想法吗?
如果您需要将视图渲染为字符串,这里是我编写的控制器的扩展方法.
注意:我会尝试找到我用来帮助我的确切链接,并在找到它时更新我的答案.
这是另一个描述此方法的链接.
这应该做的伎俩:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果要从控制器中调用此方法,只需执行以下操作:
var strView = this.RenderViewToString("YourViewName", yourModel);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4710 次 |
| 最近记录: |