I am sorry if this has been posted before. I have searched many websites and forms to fix it but I can not get it. I have a simple contact form that allows potential customers to fill out their info click submit and then email a copy of what they inputted to us. I have the email part working fine. However, the part that's not working is message after the form is submitted. I'm try to use a try and catch to display a message when they submit or a err message when it didn't work. Not sure why it is not working. Thank you for the help. My controller code is below.
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("[email protected]", "Website Contact Form");
msg.To.Add("[email protected]");
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("[email protected]", "****");
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();
}
}
}
The problem is that view that you return:
You should return the same view after error on "
postback
", with the invalid modelOne time you call that
Message
view withMessageModel
and in this line you called it withContactModel
, so there must be an error over here...Side notes:
Exception
exception it isn't good practice. Not every exception you can and should handle.isOK
flag that doesn't do a thing.catch
block, not afterwardsUpdated based on the comments:
Instead of return View you should Redirect: