我想输出两个不同的视图(一个作为字符串,将作为电子邮件发送),另一个是显示给用户的页面。
这在ASP中可能吗?NET MVC beta版?
我试过很多例子:
1. 在ASP。NET MVC Beta版 < br / >
如果我使用这个例子,我会收到“HTTP后不能重定向”
. Headers has been sent.
2. MVC框架:捕获视图的输出 < br / >
如果我使用这个,我似乎无法做一个重定向动作,因为它 试图呈现一个可能不存在的视图。如果我返回视图 完全搞砸了,看起来一点都不对。
有人对我提出的这些问题有什么想法/解决方案吗?或者有什么更好的建议吗?
很多谢谢!
下面是一个例子。我要做的是创建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);
}
接受蒂姆·斯科特的回答(我做了一些修改和格式化):
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调用订单确认电子邮件。主人的位置。
string myString = RenderViewToString(this.ControllerContext, "~/Views/Order/OrderResultEmail.aspx", "~/Views/Shared/Site.Master", this.ViewData, this.TempData);