2014-01-07 39 views
3

尝试使用http://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String上的示例将VIEW作为字符串传递,并作为电子邮件发送。应该通过电子邮件将销售发票发送给用户。传递VIEW作为STRING

Iv'e将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(); 
    } 
在视图解析器的 RenderViewToStringInternal功能

的.cs。我一直认为这是观点的道路,但不是。

任何想法? 感谢

回答

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); 
相关问题