提交后表单不检查模型状态或清除表单

时间:2012-02-08 21:58:45

标签: asp.net-mvc asp.net-mvc-2 asp.net-mail

我对这个问题有几个问题。但是,现在我重做了我的代码,几乎所有代码都正常工作。唯一的问题是在提交for之后它没有检查模型状态,因为即使表单成功,它也会显示错误。这是我的代码。

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

        oMail.From = new MailAddress("no-reply@hovdenoil.com", "Web Contact Form");
        oMail.To.Add("email@hovdenoil.com");
        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();
    }

1 个答案:

答案 0 :(得分: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("no-reply@hovdenoil.com", "Web Contact Form");
    oMail.To.Add("email@hovdenoil.com");
    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();
}