我想输出两种不同的视图(一种作为将作为电子邮件发送的字符串),另一种显示给用户。
在ASP.NET MVC beta中可能吗?
我尝试了多个示例:
1. 在ASP.NET MVC Beta中将RenderPartial转换为字符串
如果使用此示例,则会收到“发送HTTP标头后无法重定向”。
如果使用此方法,则似乎无法执行redirectToAction,因为它尝试呈现可能不存在的视图。如果我确实返回视图,则它完全被弄乱了,看起来根本不正确。
是否有人对我遇到的这些问题有任何想法/解决方案,或者对更好的问题有任何建议?
非常感谢!
下面是一个例子。我想做的是创建GetViewForEmail方法:
public ActionResult OrderResult(string ref)
{
//Get the order
Order order = OrderService.GetOrder(ref);
//The email helper would do the meat and veg by getting the view as a string
//Pass the control name (OrderResultEmail) and the model (order)
string emailView = GetViewForEmail("OrderResultEmail", order);
//Email the order out
EmailHelper(order, emailView);
return View("OrderResult", order);
}
蒂姆·斯科特(Tim Scott)接受的答案(由我更改并格式化):
public virtual string RenderViewToString(
ControllerContext controllerContext,
string viewPath,
string masterPath,
ViewDataDictionary viewData,
TempDataDictionary tempData)
{
Stream filter = null;
ViewPage viewPage = new ViewPage();
//Right, create our view
viewPage.ViewContext = new ViewContext(controllerContext, new WebFormView(viewPath, masterPath), viewData, tempData);
//Get the response context, flush it and get the response filter.
var response = viewPage.ViewContext.HttpContext.Response;
response.Flush();
var oldFilter = response.Filter;
try
{
//Put a new filter into the response
filter = new MemoryStream();
response.Filter = filter;
//Now render the view into the memorystream and flush the response
viewPage.ViewContext.View.Render(viewPage.ViewContext, viewPage.ViewContext.HttpContext.Response.Output);
response.Flush();
//Now read the rendered view.
filter.Position = 0;
var reader = new StreamReader(filter, response.ContentEncoding);
return reader.ReadToEnd();
}
finally
{
//Clean up.
if (filter != null)
{
filter.Dispose();
}
//Now replace the response filter
response.Filter = oldFilter;
}
}
用法示例
假设来自控制器的呼叫获得了订单确认电子邮件,并传递了Site.Master位置。
string myString = RenderViewToString(this.ControllerContext, "~/Views/Order/OrderResultEmail.aspx", "~/Views/Shared/Site.Master", this.ViewData, this.TempData);