渲染部分为String的控制器或其他地方 [英] Render Partial to String in the Controller or elsewhere
本文介绍了渲染部分为String的控制器或其他地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以基本上我有一个可以建立一个很好的表,我的局部视图。我想每星期通过电子邮件发送此表到我的用户。而不必基本上再次复制的模板,我想我的模型转发给控制器,并获得相应产生的 HTML
为字符串
。
So basically I have a partial view which can build a nice table for me. I would like to email this table out every week to my users. Instead of having to basically copy the template again, I would like to forward my model to the controller and receive the corresponding generated HTML
as a String
.
是否有可能在控制器做到这一点,我觉得这应该是pretty简单的过程。
Is it possible to do this in a Controller, I feel it should be a pretty simple process.
推荐答案
要把它放到辅助文件:
public static string RenderViewToString(ControllerContext context, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = context.RouteData.GetRequiredString("action");
ViewDataDictionary viewData = new ViewDataDictionary(model);
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
ViewContext viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
然后再从该控制器可以称之为是这样的:
And then from the controller you can call it like this:
var order = orderService.GetOrder(id);
var orderPrint = MyHelper.RenderViewToString(this.ControllerContext, "_OrderView", order);
这篇关于渲染部分为String的控制器或其他地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文