2017-04-12 12 views
2

私のサイトからいくつかのメールを送ろうと思います。レイザーを使用したテンプレートMVCでemaillsを送信

私はテンプレートを作成しました:OrderPlacedEmail.cshtml

@model OnlineCarStore.Models.PurchaseVM 

<h1>Order Placed Email Notification</h1> 
<p>@Model.Comments</p> 

Dear @Model.Name, 

<h2>Thank you.</h2> 
<p> 
You’ve made a purchase on <a href="">@Model.Comments</a> 
</p>....and so on... 

は、私はビューモデルを作成した、と私はこのようにそれを使用する:私は理解したよう

var template = Server.MapPath("~/Templates/OrderPlaced.cshtml"); 
var viewModel = new PurchaseVM 
{ 
    GuId = new Guid(guidValue), 
    Name = name, 
    Address = address, 
    Phone = phone, 
    Email = email, 
    Comments = comments, 
    Date = DateTime.Now, 
    CartList = cartList 
}; 

var body = Razor.Parse(template, viewModel); 

、カミソリ。 Parseメソッドは、テンプレートからのすべての詳細をビューモデルの値で置き換える必要があります。しかし、本文には、以下のようにテンプレートの場所の価値があります。

enter image description here 私が間違っていることを教えてもらえますか?

答えて

1

あなたは私はあなたのコントローラあなたはまた、NuGetギャラリーからActionMailerNextのlibを使用することができます

var viewModel = new PurchaseVM 
{ 
    GuId = new Guid(guidValue), 
    Name = name, 
    Address = address, 
    Phone = phone, 
    Email = email, 
    Comments = comments, 
    Date = DateTime.Now, 
    CartList = cartList 
}; 

var emailTemplate = "~/Views/Templates/OrderPlaced.cshtml"; 
var emailOutput = HtmlOutputHelper.RenderViewToString(ControllerContext, emailTemplate, emailModel, false); 
+0

ありがとうございます!それは完璧に動作します! :) – Orsi

1

public static class HtmlOutputHelper 
{ 

    public static string RenderViewToString(ControllerContext context, 
           string viewPath, 
           object model = null, 
           bool partial = false) 
    { 
     // first find the ViewEngine for this view 
     ViewEngineResult viewEngineResult = null; 
     if (partial) 
      viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath); 
     else 
      viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null); 

     if (viewEngineResult == null) 
      throw new FileNotFoundException("View cannot be found."); 

     // get the view and attach the model to view data 
     var view = viewEngineResult.View; 
     context.Controller.ViewData.Model = model; 

     string result = 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(); 
     } 

     return result; 
    } 
} 

を使用するヘルパーがあるたい場合このシナリオでは、

public class EmailController : MailerBase 
{ 
//... 
    public EmailResult OrderPlaced(Order order) 
    { 
     MailAttributes.To.Add(new MailAddress("[email protected]")); 
     MailAttributes.From = new MailAddress("[email protected]"); 

     return Email("OrderPlaced", new PurchaseVM 
     { 
      //... 
     }); 
    } 
//... 
} 

ビューは変更しないでください。

関連する問題