0

关于这个问题,我有几个问题。但是,现在我重做了我的代码,几乎所有的代码都在工作。唯一的问题是在提交 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();
    }
4

1 回答 1

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();
}
于 2012-02-09T14:06:30.123 回答