提交表单后返回消息

时间:2012-01-31 01:12:46

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

如果之前已发布,我很抱歉。我搜索了许多网站和表单来修复它,但我无法得到它。我有一个简单的联系表格,允许潜在客户填写他们的信息点击提交,然后通过电子邮件发送他们输入给我们的内容的副本。我有电子邮件部分工作正常。但是,在提交表单后,不起作用的部分是消息。我尝试使用try和catch来在提交时显示消息,或者当它不起作用时显示错误消息。不知道为什么它不起作用。感谢您的帮助。我的控制器代码如下。

public ActionResult ContactForm()
{
    return View();
}
public ActionResult Message()
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ContactForm(ContactModel emailModel)
{
    if (ModelState.IsValid)
    {
    bool isOk = false;
    try
    {
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("no-reply@bobcravens.com",  "Website Contact Form");
        msg.To.Add("thovden@hovdenoil.com");
        msg.Subject = emailModel.Subject;
        string body = "Name: " + emailModel.Name + "\n"
                    + "Email: " + emailModel.Email + "\n"
                    + "Website: " + emailModel.Website + "\n"
                    + "Phone: " + emailModel.Phone + "\n\n"
                    + emailModel.Message;

        msg.Body = body;
        msg.IsBodyHtml = false;

        SmtpClient smtp = new SmtpClient("smtpout.server.net", 25);
        NetworkCredential Credentials = new NetworkCredential("thovden@hovdenoil.com", "****");
        smtp.Credentials = Credentials;
        smtp.Send(msg);
        msg.Dispose();
        isOk = true
        ContactModel rcpt = new ContactModel();
        rcpt.Title = "Thank You";
                    rcpt.Content = "Your email has been sent.";
                    return View("Message", rcpt);
        }
        catch (Exception ex)
        {
        }
        // If we are here...something kicked us into the exception.
        //
       ContactModel err = new ContactModel();
        err.Title = "Email Error";
        err.Content = "The website is having an issue with sending email at this time. Sorry for the inconvenience. My email address is provided on the about page.";
        return View("Message", err);
        }
        else
        {
            return View();
        }
    }
 }

2 个答案:

答案 0 :(得分:1)

问题在于您返回的视图:

return View("Messgae", err):

使用无效模型

,您应该在“postback”错误后返回相同的视图
return View(err);

有一次您使用Message来调用MessageModel视图,并在此行中使用ContactModel调用它,因此此处必定存在错误...

附注:

  • 您正在捕捉全球Exception例外,这不是一个好习惯。不是每个例外都可以并且应该处理。
  • 你有一个isOK标志,不能做任何事情。
  • 将例外Handel移到catch块内,而不是之后

根据评论更新:

而不是返回View,你应该重定向:

return RedirectToAction("Message", err);
return RedirectToAction("Message", rcpt);

public ActionResult Message(ContactModel model)
{
    return View(model);
}

答案 1 :(得分:0)

我首先会发出异常,以便您可以确切地知道出了什么问题。此外,您可能希望单步执行代码。