JQuery Functions for JSON Calls


This article is focusing on people who recently moved to the MVC and JQuery world and looking for many of their existing functionalities. We had a trigger property in the side update panel to fire a partial post back with better user experience.  The question is simple, I need to fire server side logic in my button, HTML button!!!, click without any post back and using JQuery. Also I should get the return data from the executed server method inside my JavaScript to bind it to a control. All these without a post back sense from a user point of view.

The JQuery built-in methods for the above mentioned scenario are $.Ajax & $.getJSON. Both internally doing same thing and the attached code contains sample from both methods. I have a sample method inside my controller like below, which will return a list of names.

public JsonResult GetNames(DetailsModel model)
{
       return Json(model.GetNames(), JsonRequestBehavior.AllowGet);
}

About highlighted parts, JsonResult should be the return type of a method which is called from JavaScript. Also we are mentioning that it's a Get type request using

JsonRequestBehavior.AllowGet)

This method is calling one of its model methods with below definition

public List<string> GetNames()
{
       return new List<string> { "Jaish", "Mathews", "Shailesh" };
}


That's all from server side and I have one HTML button in sided my View like

<input type="button" value="Get names" onclick="getNames();" />

You can see its calling one javaScript method, getNames();
We are initiating the JSON call inside this method. Below is the pasted code using both methods i.e. $.ajax and $.getJSON

$.ajax({
                type: "GET",
                url: path + "/GetNames",|
                cache: false,
                processData: false,
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (names) {
                    $.each(names, function (key, value) {
                        $("#names").append($("<option></option>").val(key).html(value));
                    });

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        alert(textStatus);
                }
            });

$.getJSON(path + "/GetNames", "{}", fillNames);

Using $.ajax, the parameters are with a syntax of name value collection. But $.getJSON using normal syntax. You have the option to choose what is needed. Also the results will be reached in side callback methods. What we are doing here is raising a GET request to the URL. URL is <<your current URL without actionname>>/<<name of the controller method>> i.e. you are replacing the page action with a new one specific to JSON. Let see the running windows below.

1st Screen

JSON1.gif

2nd Screen with JSON Call

JSON2.gif

You can see the dropdown list doesn't have any items and now we will pick those items from server side like in below screen. Click the Get names button

Final result

JSON3.gif

See the data accessed from the sever side is now displaying. Please check the code attached and you have a lot to play with this.

Up Next
    Ebook Download
    View all
    Learn
    View all