渲染动作为String [英] Render Action to String
问题描述
我有返回partialview一个动作,我想呈现的动作结果字符串,我试过很多例子表明对其他线程关于这个主题,但都具有相同的行为,执行去查看,但没有行动,这可能吗?
I have an action that return a partialview and I want to render the action result to string, I tried lot of examples show on others threads about this subject, but all have the same behavior, executes de View but not the action, is this possible?
例如:
1)动作 - 局部视图渲染字符串
Example: 1) Action - Partial View to render to string
public PartialViewResult Email(string Subject, string Body)
{
ViewBag.Subject = Subject;
ViewBag.Body = Body;
ViewBag.ExtraData = Session["ExtraData"];
return PartialView();
}
2)局部视图
@{
Layout = null;
string Subject = (string)@ViewBag.Subject
string Body = (string)@ViewBag.Body
}
<html>
<head>
<title>@Subject</title>
</head>
<body style="margin:0px">
@Body
</body>
3)控制器类中获得串动的结果。
3) Controller class obtaining string action result
var emailHTML = RenderViewToString(ControllerContext, "Email", new string[] { subject, msg });
4)计算器线程助手方法
4) Helper method from stackoverflow thread
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();
}
}
如果我调试code,它直接进入不带ViewBag数据的视图,不执行电子邮件操作方法。
If I debug the code, it goes directly to the View with no ViewBag data, and doesn't execute the Email Action method.
任何想法?
推荐答案
这助手是直接渲染视图,但它不是一个动作。也就是说,甚至不打电话,你想它来调用该操作。而是,code只找到一个视图,并直接使得它与提供的模型一个作家。
That helper is useful for rendering a view directly, but not an action. That is, is doesn't even call that action that you want it to call. Instead, that code just finds a view and renders it directly to a writer with the supplied model.
我们想要做的实际上是调用电子邮件()
PartialViewResult
和渲染什么。
What we want to do is actually call the Email()
PartialViewResult
and render that.
注意:
using (var sw = new StringWriter())
{
PartialViewResult result = Email("Subject", "Body");
result.View = ViewEngines.Engines.FindPartialView(ControllerContext, "Email").View;
ViewContext vc = new ViewContext(ControllerContext, result.View, result.ViewData, result.TempData, sw);
result.View.Render(vc, sw);
var html = sw.GetStringBuilder().ToString();
}
这篇关于渲染动作为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!