2012-05-08 56 views
2

不知道是否有人遇到了這個問題,但我想用發送電子郵件MVCMailer。我能夠安裝並更新T4Scaffolding軟件包,沒有任何問題。問題與MVCMailer

我有一個創建報表的aspx頁面,我想附加到電子郵件,該報告。然而,當我轉身叫我SendReport方法在UserMailers類,它拋出一個錯誤的PopulateBody電話,說的RouteData爲空

這裏是我的代碼

public class UserMailer : MailerBase, IUserMailer 
{ 
    /// <summary> 
    /// Email Reports using this method 
    /// </summary> 
    /// <param name="toAddress">The address to send to.</param> 
    /// <param name="viewName">The name of the view.</param> 
    /// <returns>The mail message</returns> 
    public MailMessage SendReport(string toAddress, string viewName) 
    { 
     var message = new MailMessage { Subject = "Report Mail" }; 
     message.To.Add(toAddress); 

     ViewBag.Name = "Testing-123"; 

     this.PopulateBody(mailMessage: message, viewName: "SendReport"); 

     return message; 
    } 
} 

我得到的錯誤是「值不能爲空參數名:的RouteData」

我看了網上,並沒有發現任何與此有關的問題或任何人誰​​遇到了這個問題。

+0

我也越來越這個問題,但奇怪的是隻有一兩個我們發送電子郵件的,你有沒有得到它的底部? – Tim

回答

2

它被稱爲的mvc梅勒是有原因的。 您不能在正常的asp.net(.aspx)項目中使用它,只能在MVC項目中使用它。

+0

菲利普 - 請指出我的帖子在哪裏說,該項目不是一個MVC項目?有很多人在MVC項目中使用Web表單的例子。 – George

+0

我的不好,我認爲錯了:)仍然,問題仍然存在,如果您調用.aspx網絡表單,路由不會加載。 –

0

正如Filip所說,它不能在ASP.NET ASPX頁面的代碼隱藏中使用,因爲沒有ControllerContext/RequestContext

對我來說只是創建一個控制器動作,然後使用WebClient,使從ASPX頁面的HTTP請求的最簡單方法。

protected void Button1_Click(object sender, EventArgs e) 
    { 
     WebClient wc = new WebClient(); 

     var sendEmailUrl = "https://" + Request.Url.Host + 
          Page.ResolveUrl("~/email/SendGenericEmail") + 
          "[email protected]" + "&template=Template1"; 

     wc.DownloadData(sendEmailUrl); 
    } 

然後,我有一個簡單的控制器

public class EmailController : Controller 
{ 
    public ActionResult SendGenericEmail(string emailAddress, string template) 
    { 
     // send email 
     GenericMailer mailer = new GenericMailer(); 

     switch (template) 
     { 
      case "Template1": 

       var email = mailer.GenericEmail(emailAddress, "Email Subject"); 
       email.Send(mailer.SmtpClient); 
       break; 

      default: 
       throw new ApplicationException("Template " + template + " not handled"); 
     } 

     return new ContentResult() 
     { 
      Content = DateTime.Now.ToString() 
     }; 
    } 
} 

當然也有許多問題,如安全性,協議(控制器將無法訪問原來的頁面),錯誤處理 - 但如果你發現自己卡住了,這可以工作。