尽管这篇2月份的答案(我认为是在1.0版本后)声称可以将视图渲染为字符串然后重定向,但我仍无法实现。我以为是自己操作有误,但随后我看到了7月份Haack的答案,声称不可能实现。
如果有人已经成功实现并能够帮我解决问题,那么太好了(我会贴出代码和错误信息)。然而,我现在需要使用一些变通的方法。虽然有一些方法,但没有最理想的。有没有人解决过这个问题,或者对我的想法有任何评论?
感谢您,詹姆斯。
如果有人已经成功实现并能够帮我解决问题,那么太好了(我会贴出代码和错误信息)。然而,我现在需要使用一些变通的方法。虽然有一些方法,但没有最理想的。有没有人解决过这个问题,或者对我的想法有任何评论?
- 这是用来渲染电子邮件的。虽然我可以在Web请求之外发送电子邮件(将信息存储在数据库中并稍后获取),但有许多类型的电子邮件,我不想将模板数据(用户对象、几个其他LINQ对象)存储在数据库中以便以后再渲染。我可以创建一个更简单、可序列化的POCO,并将其保存在数据库中,但为什么要这样做呢?...我只想要渲染后的文本!
- 我可以创建一个新的RedirectToAction对象,检查头是否已发送(无法弄清楚如何做到这一点--尝试/捕获?),如果是,则构建出一个简单的页面,其中包含meta重定向、javascript重定向以及"点击此处"链接。
- 在我的控制器中,我可以记住是否已经渲染了电子邮件,并且如果是,通过显示视图手动执行第2步。
- 我可以在任何可能的电子邮件渲染之前手动发送重定向头。然后,不使用MVC基础设施进行重定向操作,而是直接调用result.end。这似乎最简单,但真的很混乱。
- 还有其他方法吗?
编辑:我尝试了丹的代码(非常类似于我已经尝试过的1月/2月的代码),但仍然遇到相同的错误。我唯一能看到的实质性差异是他的示例使用视图,而我使用部分视图。稍后我将尝试使用视图进行测试。
以下是我的代码:
控制器
public ActionResult Certifications(string email_intro)
{
//a lot of stuff
ViewData["users"] = users;
if (isPost())
{
//create the viewmodel
var view_model = new ViewModels.Emails.Certifications.Open(userContext)
{
emailIntro = email_intro
};
//i've tried stopping this after just one iteration, in case the problem is due to calling it multiple times
foreach (var user in users)
{
if (user.Email_Address.IsValidEmailAddress())
{
//add more stuff to the view model specific to this user
view_model.user = user;
view_model.certification302Summary.subProcessesOwner = new SubProcess_Certifications(RecordUpdating.Role.Owner, null, null, user.User_ID, repository);
//more here....
//if i comment out the next line, everything works ok
SendEmail(view_model, this.ControllerContext);
}
}
return RedirectToAction("Certifications");
}
return View();
}
SendEmail()
public static void SendEmail(ViewModels.Emails.Certifications.Open model, ControllerContext context)
{
var vd = context.Controller.ViewData;
vd["model"] = model;
var renderer = new CustomRenderers();
//i fixed an error in your code here
var text = renderer.RenderViewToString3(context, "~/Views/Emails/Certifications/Open.ascx", "", vd, null);
var a = text;
}
自定义渲染器
public class CustomRenderers
{
public virtual string RenderViewToString3(ControllerContext controllerContext, string viewPath, string masterPath, ViewDataDictionary viewData, TempDataDictionary tempData)
{
//copy/paste of dan's code
}
}
错误
[HttpException (0x80004005): Cannot redirect after HTTP headers have been sent.]
System.Web.HttpResponse.Redirect(String url, Boolean endResponse) +8707691
感谢您,詹姆斯。