2012-02-08 49 views
0

我對這個問題有幾個問題。但是,現在我重新編寫了代碼,幾乎所有代碼都可以工作。唯一的問題是,在提交for之後,它沒有檢查模型狀態,因爲即使表單成功顯示也有錯誤。這是我的代碼。表單在提交後不檢查模型狀態或清除表單

[HttpPost] 
    public ActionResult ContactForm(ContactModel emailModel) 
    { 
     MailMessage oMail = new MailMessage(); 

     oMail.From = new MailAddress("[email protected]", "Web Contact Form"); 
     oMail.To.Add("[email protected]"); 
     oMail.Subject = emailModel.Subject; 
     string body = "Name: " + emailModel.Name + "\n" 
        + "Email: " + emailModel.Email + "\n"       
        + "Phone: " + emailModel.Phone + "\n\n" 
        + "Company: " + emailModel.Company + "\n" 
        + "Website: " + emailModel.Website + "\n" 
        + emailModel.Message; 
     oMail.Body = body; 

     SmtpClient client = new SmtpClient("smtpout.secureserver.net"); 
     client.Credentials = new NetworkCredential("username", "password"); 
     client.Send(oMail); 

     string message = "There are a few errors"; 

     if (ModelState.IsValid) 
     { 
      message = "Thanks! We'll get back to you soon."; 
      ModelState.Clear(); 
     } 

     if (Request.IsAjaxRequest()) 
     { 
      return new JsonResult { ContentEncoding = Encoding.UTF8, Data = new { success = true, message = message } }; 
     } 

     TempData["Message"] = message; 

     return View(); 
    } 
+0

我找到了我自己的答案。重新排列「If(ModelState.IsValid)」 – 2012-02-08 22:08:49

+0

[HttpPost] public ActionResult ContactForm(ContactModel emailModel) { string message =「有幾個錯誤」; if(ModelState.IsValid) { MailMessage content message =「謝謝!我們會盡快給您回覆。」; ModelState.Clear(); } – 2012-02-08 22:11:10

回答

0

我的不好。我把If(ModelState.IsValid)過早。聽到我的最終代碼是有效的。

[HttpPost] 
public ActionResult ContactForm(ContactModel emailModel) 
{ 
    string message = "There are a few errors"; 

    if (ModelState.IsValid) 
    { 

    MailMessage oMail = new MailMessage(); 

    oMail.From = new MailAddress("[email protected]", "Web Contact Form"); 
    oMail.To.Add("[email protected]"); 
    oMail.Subject = emailModel.Subject; 
    string body = "Name: " + emailModel.Name + "\n" 
       + "Email: " + emailModel.Email + "\n"       
       + "Phone: " + emailModel.Phone + "\n\n" 
       + "Company: " + emailModel.Company + "\n" 
       + "Website: " + emailModel.Website + "\n" 
       + emailModel.Message; 
    oMail.Body = body; 

    SmtpClient client = new SmtpClient("smtpout.secureserver.net"); 
    client.Credentials = new NetworkCredential("username", "password"); 
    client.Send(oMail); 

     message = "Thanks! We'll get back to you soon."; 
     ModelState.Clear(); 
    } 

    if (Request.IsAjaxRequest()) 
    { 
     return new JsonResult { ContentEncoding = Encoding.UTF8, Data = new { success = true, message = message } }; 
    } 

    TempData["Message"] = message; 

    return View(); 
}