I have a form that collects a data using ASP.NET MVC. It looks like this:
[AcceptVerbs(HttpVerbs.Post)]
[AutoValidate]
public ActionResult Contact(ContactMessage msg)
{
if(ModelState.IsValid)
{
try
{
this.messengerService.SendMail(msg);
RedirectToAction("Index");
}
catch (Exception ex)
{
ModelState.AddUnhandledError(ex);
}
}
return View(msg);
}
I'm using asp.net mvc validations and model state validation to take care of the invalid rule messages being displayed. It all is working.
Now I want to submit the action, using ajax form, and display a success message when the action is completed successfully. I tried using the code below, and it works when operation succeeds, but when it fails (model has errors), the whole page is rendered again in the DIV that displays success message! Is this possible?
[AcceptVerbs(HttpVerbs.Post)]
[AutoValidate]
public ActionResult Contact(ContactMessage msg)
{
if(ModelState.IsValid)
{
try
{
this.messengerService.SendMail(msg);
return Content("Message sent");
}
catch (Exception ex)
{
ModelState.AddUnhandledError(ex);
}
}
return View(msg);
}