InspiredBy
InspiredBy

Reputation: 4320

How to return errors or notifications from JSON Action method to Ajax forms?

Let's say we have a standard Ajax form with the following Syntax:

  @using(Ajax.BeginForm("AddCityJson", "City",new AjaxOptions
        {
            HttpMethod = "post",
            OnSuccess = "JScriptOnSuccess();",
            OnFailure = "JScriptOnFailure"
        }))
    {
     ...form fields go here...   
     }

A simple form that gathers some information about a city, submits and saves it.

On the controller side we receive the info. If everything went well we return true in order for OnSuccess AjaxOption to trigger and if failed false is returned:

public JsonResult AddCityJson(Formcollection collection)
{
 var city = new City
 {
  ...populate city fields from passed in collection
 }
 var cityRepository = new CityRepository;
 city = cityRepository.SaveOrEdit(city);

 if(city==null)
 {return Json(false)} 

 return Json(true);

}

Inside of the controller AddCityJson method I need to add various checks. Possibly to check if the city name already exists or any other validation and if I ran into an Error or a Warning return it back to UI.

How can I pass any error/warning messages up to UI if my Ajax form expects to get back ajax true or false and whether that post was successful?

I would like to avoid using ViewData, ViewBags. Thank you.

Upvotes: 1

Views: 1185

Answers (1)

Shan Plourde
Shan Plourde

Reputation: 8726

You can return any number of values in your JSON result, for example:

return Json(new { success = false, message = errorMessage });

And then interpret this on the client side. No need to use ViewData, ViewBags, etc. Just format the result on the client side, so you're just transmitting data over JSON.

EDIT: I didn't realize you were using Ajax.BeginForm(). You should still be able to hook into the JSON results client side to parse the results. See How to use Ajax.BeginForm MVC helper with JSON result?.

Although I would suspect most people would use jQuery to accomplish the same thing, such as described on various StackOverflow posts like Darin's response at Using Ajax.BeginForm with ASP.NET MVC 3 Razor. Which is what I would recommend as well, since the jQuery library is very robust and cross platform tested.

Upvotes: 1

Related Questions