.tabs-outer { overflow: hidden; position: relative; }

Saturday, September 13, 2014

AJAX in MVC using jQuery and JSON Object

Hey Guys,

In my previous post I have expalined about the difference between Webforms and MVC. In this post I am gonna help you on how to implement AJAX in MVC using jQuery.

Before starting with AJAX in MVC, lets have quick glance at what Ajax is all about.

What is AJAX? 
  • AJAX is an acronym for 'Asynchronous JavaScript and XML'. It is a technique for creating fast and dynamic web pages.
  • AJAX allows to update specific parts of web pages asynchronously by exchanging small amounts of data with the server behind the scenes (request from UI get the modified data back from server). It is possible to update parts of a web page, without reloading the whole page.
  • Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
  • Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
Earlier, XML is used to exchange the data with Server, ie using XMLHttpRequest object. But these days JSON(JavaScript Object Notation) is used to send and receive the data from UI to server. 

What is JSON?
JSON is short for JavaScript Object Notation, It is a lightweight data-interchange format that is easy for humans to read and write, and for machines to parse and generate. JSON is based on the object notation of the JavaScript language. However, it does not require JavaScript to read or write because it is a text format that is language independent. Its more like key-value pair.

 Here is the example for JSON which is equivalent of XML.





Ajax in MVC:

Ajax in MVC can be used in two ways, one is using unobtrusive java script and other one is using jQuery Ajax. Lets concentrate on jQuery Ajax.

To perform Ajax using jQuery we use $.ajax() method. There are different shorter forms $.ajax() of to perform specific operations.

  • To Load data - $.load()
  • To Get data - $.get()
  • To Post data - $.post()
These operations are having limited options. So we do use generalized AJAX if we want to have more control.
Ajax syntax is explained below.

     $.ajax({
            url: url,
            type: 'POST',
            data: Data,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (result) {

            },
            error: function failCallBk(XMLHttpRequest, textStatus, errorThrown) {
                alert("Some error occured while processing your request.");
            }
        });

**url: Type: String 
It is pointing to Action method in your controller. It will be having value like "Area/Controller/Action"
  
**type: Type: String
 Ajax type is defined using type GET to get the data, POST is to post data.

** data: Type: PlainObject or String or Array
This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used.

**dataType: (xml, json, script, or html) Represents what kind of data you are you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

**contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.

These are the basic parameters, there are many other parameters also you can use to optmiize the request based on your requirement.

For an example, lets assume a typical situation where you want to submit your form data. Consider you want to submit your first name and last name.
Here are the steps to submit data using AJAX and JSON Object.

View Code: 

<table>
    <tr>
        <td>
            First name
            <br />
            @Html.TextBox("FirstName", "", new { id = "firstName" })
        </td>
        <td>
            Last Name
            <br />
            @Html.TextBox("LastName", "", new { id = "lastName" })
        </td>
        <td>
            <button type="submit" id="submitData">Submit Data</button>
        </td>
    </tr>
</table>

Model Code: 

 public class UserDataViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

Controller Code where Ajax will be pointing:

     [HttpPost]
     public JsonResult SubmitUserData(UserDataViewModel userData)
        {
            /* To use the UserDataViewModel  dierctly here make sure that 
               you create JSON data in AJAX in the same way.
               Property names should be same in both model aswell as in the JSON object
             */
       
            // Perform your actions here.

            return Json("data submitted");
            
        }

jQuery Code:

        //Get First and Last Name.
        var firstName = $("#firstName").val();
        var lastName = $("#lastName").val();

        // create JSON Object

        var ajxUserData = {
            "FirstName":firstName,
            "LastName":lastName
        }

        // Then stringify data
        var data = JSON.stringify({ userData: ajxUserData });

        //Then Create URL
        var url = "User/UserData/SubmitUserData" // User is a AreaName, UserData is a Controller and SubmitUserData is ActionMethod

        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                // In result you will get result that you return, for this example you get "data submitted"
            },
            error: function failCallBk(XMLHttpRequest, textStatus, errorThrown) {
                alert("Some error occured while processing your request.");
            }
        });

    });

Hope this helps.! Happy Coding.
Please do like and share it, if you find it useful.

Thanks,
Ram

No comments:

Post a Comment