0

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

1 Answer 1

2

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");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.