Spodworld

a collection of technical fixes and other randon stuff

Example of a Json request to an MVC controller using Jquery

When trying to do an ajax request to an MVC controller for some json data, I found there are a lot of incomplete examples and different ways of doing things, so here is my take on it.

Firstly, you need to create an ActionResult (or JsonResult) in your controller like this:

public ActionResult DoesClientHaveAccount(int clientId)
{}

or

public JsonResult DoesClientHaveAccount(int clientId)
{}

Returning the data required you to convert to a Json object. A simple way to do this is with the Json function as follows.
public JsonResult DoesClientHaveAccount(int clientId)
{
return Json(new { success = false, Message = "Account found with no address!", noOfAccounts = 1 }, JsonRequestBehavior.AllowGet);
}

I've deliberately made this a little more complicated to show how we pass multiple values back to the calling script.

Note the statement...

JsonRequestBehavior.AllowGet

Without this you may get calls to your controller returning an Internal server error message.
This is because without it , you wont have permission to call the Action.

Another important parameter is the content Type. Without it, sometimes you may find your response  at the client side appears as
[Object] [object]

This sometimes occurs on IIS if you dont have the Mime types set for Json/Ajax etc... It can also occur when developing with Visual studio's built in web server.

To fix this add the Content Type as follows:
 return Json(new { success = false, Message = "Account found with no address!", noOfAccounts = 1 },"text/text", JsonRequestBehavior.AllowGet);
  
when calling this from the javascript code on the client browser, an example is as follows:

$.ajax({
            type: "POST",
            url: "/Account/DoesClientHaveAccount/",
            data: { "clientID": clientId },
            traditional: true,
            async: false,
            success: function (returndata) {
                success = returndata.success;
                if (true == success) {
                    hasAccount = true;
                    $("#AccountsFound").val(returndata.noOfAccounts);
                    var id_addCombo = arr[0].Value;
                    var myName = arr[0].Text;
                    var myAddress = id_addCombo.split("$$")[1]
                    var myID = id_addCombo.split("$$")[0];
                }
                else {
                    hasAccount = false;
                }
            },
            error: function (xhr, textStatus, error) {
                alert("There was an error while checking for a matching account: " + error);
            }
        });

It's always good to have two levels of error checking.
The success: and error:     events   are for triggering actions when all is well and handling errors when there is a serious comms error.

In this example, i pass back a success flag to indication if any of our server side logic detected an error.
 
This example is based on the Jquery .ajax call. To use this, yuo will need to include the JQuery script files in your application.
      
Loading