Question

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);
}

Was it helpful?

Solution

Your problem is the last line returning the normal view.

Try this:

[AcceptVerbs(HttpVerbs.Post)]
[AutoValidate]
public JsonResult Contact(ContactMessage msg)
{
    if(ModelState.IsValid)
    {
        try
        {
            this.messengerService.SendMail(msg);
            return Json("Message sent");
        }
        catch (Exception ex)
        {
            ModelState.AddUnhandledError(ex);
        }
    }

    return Json("There were model errors");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top