我想利用Razor View的模型绑定/渲染功能来生成我从ASP.NET MVC应用程序发送的电子邮件的HTML正文内容。
有没有办法将视图呈现为字符串,而不是将其作为GET请求的ActionResult返回?
为了说明我正在寻找将会做以下事情的东西:
public ActionResult SendEmail(int id) { EmailDetailsviewmodel emailDetails = EmailDetailsviewmodel().CreateEmailDetails(id); // THIS IS WHERE I NEED HELP... // I want to pass my viewmodel (emailDetails) to my View (EmailBodyRazorView) but instead of Rending that to the Response stream I want to capture the output and pass it to an email client. string htmlEmailBody = View("EmailBodyRazorView",emailDetails).ToString(); // Once I have the htmlEmail body I'm good to go. I've got a utilityt that will send the email for me. MyEmailUtility.SmtpSendEmail("stevejobs@apple.com","Email Subject",htmlEmailBody); // Redirect another Action that will return a page to the user confirming the email was sent. return RedirectToAction("ConfirmationEmailWasSent"); }
解决方法
如果您只需要将视图呈现为字符串,请尝试以下操作:
public string ToHtml(string viewToRender,ViewDataDictionary viewData,ControllerContext controllerContext) { var result = ViewEngines.Engines.FindView(controllerContext,viewToRender,null); StringWriter output; using (output = new StringWriter()) { var viewContext = new ViewContext(controllerContext,result.View,viewData,controllerContext.Controller.TempData,output); result.View.Render(viewContext,output); result.ViewEngine.ReleaseView(controllerContext,result.View); } return output.ToString(); }
您需要从控制器操作中传递视图的名称以及ViewData和ControllerContext。