ASP.Net MVC: Using Json Standard Responses for your Ajax Calls

For the past couple of years, after we started our move towards ASP.Net MVC, we have been using more and more ajax to enrich our user interface and we love it.

At the begining we use to send our responses as simple strings (true/false) or very customized Json responses. However, for the past year or so we’ve been using Standard Json Responses and it has been working great. I’ve passed this idea to a couple of friends and everyone seems to like it so here it is.

Objective & Advantages

The objective will be to have standard Json Responses to our AJAX calls that we can easily re-use accross our application, independent of what action or what objects we are working with… And by having and standard responses, we can have a standard way to handle them.

Download the Code

The JSON Response Factory

This is what we have been using to generate the Standard Response  (yes, is VERY simple) . By having the factory and reusing it across the application we are basically enforcing the standard:

public class JsonResponseFactory
{
 public static object ErrorResponse(string error) {
 return new { Success = false, ErrorMessage = error };
 }

public static object SuccessResponse() {
 return new { Success = true};
 }

public static object SuccessResponse(object referenceObject)
 {
 return new { Success = true, Object = referenceObject };
 }

}

The main thing to notice is that we are using dynamic objects; we do so (instead of a plain class) so we can easily return only what it is necessary.

Now let’s dig in. It is very simple, but lets pick it apart function by function:


public static object ErrorResponse(string error) {
return new { Success = false, ErrorMessage = error };
}

This function generates an object that has a Success flag, which is set to false (is an error), and an ErrorMessage. We force the error responses to have an error message, although you can chose to do it differently.

public static object SuccessResponse() {
 return new { Success = true};
 }

This is probably the simplest one, but one of the one we use the most. The function generates an object with Success equals to true and that is it. It is used a lot for functions such as “Delete”.

public static object SuccessResponse(object referenceObject)
 {
 return new { Success = true, Object = referenceObject };
 }

Finally there is the function that generates a response with a reference object inside. This function is useful when you need to send an object (Get type of funcitons).

The Controller: Let’s use those cool responses!

So now we know how to build our responses. Here is how you would send it back on your controller – you all probably already know 😉

[HttpPost]
public JsonResult DeleteSuccess(int? id) {
 return Json(JsonResponseFactory.SuccessResponse());
}

[HttpPost]
public JsonResult DeleteError(int? id)
{
 return Json(JsonResponseFactory.ErrorResponse("Some Error... Can't delete!"));
}

[HttpPost]
public JsonResult GetCarSuccess(int? id)
{
 //NOTE: For this example I am using a dynamic object, but the idea is that it could be any object
 var car = new { Name = "Toyota Yaris", Price = "10000", Color = "Red" };
 return Json(JsonResponseFactory.SuccessResponse(car));
}

Now, notice that our functions are returning a JsonResults (I also specified the Verb (HttpPost), you can omit it if you want), but the magic happens here:

return Json(JsonResponseFactory.SuccessResponse(car));

Because “Json” takes any object and converts it into JSon, is basically allowing us to send anything we want back. In this example, we are returning a standard response,with a reference object (‘car’) in it and it will be converted into Json for us… that was easy 🙂

On the Client Side! Handle the Response

The server side is ready, now let’s see a sample of how to handle the response on the client side.


$(function () {
   $(".test-link").click(function (e) {
     e.preventDefault;
     $.post("controller/action", function (data) {
        if (data.Success == true) {
           alert("Success");
           if (data.Object != null){
              //here I could call the properties of my object, as below:
              alert(data.Object.Name); //assuming your object has a property name
            }
         }
         else {alert(data.ErrorMessage);}
       });
       return false;
    });
});

This code simulates a click event that posts into our controller using jQuery. Because the response (data) is automatically converted into an jQuery object, you can use it immediately. Notice that I am calling the property names that I assign on the factory such as “Success”, “ErrorMessage” and “Object”.
Inside the data.Object there will be any object that you specified on your server side code, and you can use it accordingly. In the snippet above, we are assuming the object will have a property called “Name”.
That is pretty much it! Simple, but it has saved us a lot of time. You can create your own standards, but the important thing is that it is maintained across your application and that the development team is made aware of it so they can quickly use it on their tasks.

Author: ricardocovo

Senior Software Architect/Developer with extensive experience in web related technologies.

17 thoughts on “ASP.Net MVC: Using Json Standard Responses for your Ajax Calls”

  1. hmm, i think it is better to handle the “error” from the mvc controller in the error callback function of the ajax request by setting the proper http status code. is your approach used in any major sites?

    1. I have used it on Memplai.com, Toystrunk.com & ServersOk.com (partially). Now days, if I am using Web API, I use the Http Status Code, but I still find this useful in many ways.

  2. salute salute salute to your knowledge regarding new technology.I have now started to try MVC..and your tutorials and videos helps me a lot..Thanks a lot…Please post some more videos regarding MVC4 webapi and other cool stuff so that we can learn a lot from a champ like you Sir.

    1. Thanks Darshan, I have a few projects that are running on MVC4 with Web.Api – I just need the time to post. Do you have any particular interest?

      1. Hi Ricardo, wouldn’t mind seeing
        (i) kendo grid with web.api
        (ii) and custom get methods on web.api

  3. Sweet blog! I found it while searching on Yahoo News.
    Do you have any tips on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there! Thanks

  4. Mate, this is awesome. As simple as it is its so robust and reusable. I’m gonna use this standard across all my apps

  5. Nice post. I was checking constantly this weblog
    and I’m inspired! Extremely useful info specially the last section 🙂 I care for such information a lot. I used to be seeking this particular info for a long time. Thank you and good luck.

  6. Nice solution. I used a slightly one off from this and it has helped resolve many issues that I did not like namely responsiveness of pages. However I have ran into a need to do something a little different in the updateSuccess(data) function. I have posted the question on SO at the following link. I don’t want to blow up your comments with the run down but if you could help me out I would appreciate it.

    http://stackoverflow.com/questions/18669168/javascript-to-build-mvc-actionlink-conditionally

  7. Dear Ricardo,
    I’m starting my 1st steps into JQuery, Ajax, using ASP .Net.
    Though I notice you don’t have to cater for the “d” member in the JSON response, why is that?
    Apologies in advance if this is a noob question!

Leave a comment