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 に答える