尝试使用http://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String
上的示例将VIEW作为字符串传递,并作为电子邮件发送。哪个应该通过电子邮件将销售发票发送给用户。
我已将ViewRenderer类添加到我的项目中。然后将ContactSeller功能添加到我的控制器,并将发票视图复制并重命名为ViewOrderThroughEmail.cshtml
[HttpPost]
[AlwaysAccessible]
public ActionResult SendEmailAttachment(QBCustomerRecord cust)
{
ContactSellerViewModel model = new ContactSellerViewModel();
string invoiceEmailAsString = ContactSeller(model);
_userService.SendEmail(username, nonce => Url.MakeAbsolute(Url.Action("LostPassword", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl), invoiceEmailAsString);
_orchardServices.Notifier.Information(T("The user will receive a confirmation link through email."));
return RedirectToAction("LogOn");
}
[HttpPost]
public string ContactSeller(ContactSellerViewModel model)
{
string message = ViewRenderer.RenderView("~/Orchard.Web/Modules/RainBow/Views/Account/ViewOrderThroughEmail.cshtml",model,
ControllerContext);
model.EntryId = 101;
model.EntryTitle = message;
return message;
}
但是这会引发错误,VIEW不能为NULL:
using (var sw = new StringWriter())
{
var ctx = new ViewContext(Context, view,
Context.Controller.ViewData,
Context.Controller.TempData,
sw);
view.Render(ctx, sw);
result = sw.ToString();
}
在ViewRenderer.cs中的RenderViewToStringInternal
函数中。我还是认为这是观点的路径,但事实并非如此。
有什么想法吗? 感谢
答案 0 :(得分:2)
我在项目中使用以下扩展方法:
public static string RenderView(this Controller controller, string viewName, ViewDataDictionary viewData)
{
var controllerContext = controller.ControllerContext;
var viewResult = ViewEngines.Engines.FindView(controllerContext, viewName, null);
StringWriter stringWriter;
using (stringWriter = new StringWriter())
{
var viewContext = new ViewContext(
controllerContext,
viewResult.View,
viewData,
controllerContext.Controller.TempData,
stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
}
return stringWriter.ToString();
}
public static string RenderView(this Controller controller, string viewName, object model)
{
return RenderView(controller, viewName, new ViewDataDictionary(model));
}
然后在你的行动方法中:
var viewString = this.RenderView("ViewName", model);