ASP.NET MVC Application - Using JQuery, AJAX

In this article we will clarify our knowledge about using and posting a form with JQuery and Ajax.

Before diving into the core topic let’s have an overview about JQuery and Ajax. What is it?

What is JQuery?

Well, JQuery is a framework (tools) for writing JavaScript, Written as "write less, do more", jQuery is to make easier to use JavaScript.

What is JavaScript?

JavaScript is an object-oriented computer programming (Scripting) language commonly used to create interactive effects within web browsers.

Let’s have a sample example:

We have a submit button in our JQuery AJAX MVC application. Let’s try to show a message when it is clicked.

Here is our button with defined id="btnSubmit":

  1. <input type="submit" value="Create" class="btn btn-default" id="btnSubmit" />

Now we need to write some script to do that, here is some JavaScript code:

  1. var myBtn = document.getElementById('btnSubmit');  
  2. myBtn.addEventListener('click', function(e) {  
  3.     e.preventDefault(); //This prevents the default action  
  4.     alert('Hello'); //Show the alert  
  5. });

By this code the result will show “Hello”:

Now if we can get the same result by using jQuery instead of it. Let’s have a look:

  1. $('#btnSubmit').click(function(event) {  
  2.     event.preventDefault(); //This prevents the default action  
  3.     alert("Hello"); //Show the alert  
  4. });

Note: Here use of 'e' is just a short for event which raised the event. We can pass any variable name. Notice that the ‘e’ is changed to name ‘event’ in JQuery part.

This piece of code is also producing the same result “Hello”. This is why jQuery is known as "write less, do more".

Finally the script:

  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         $(function() {  
  4.   
  5.             /*var myBtn = document.getElementById('btnSubmit');  
  6.             myBtn.addEventListener('click', function(e) {  
  7.                 e.preventDefault();  
  8.                 alert('Hello');  
  9.             });*/
  10.   
  11.             $('#btnSubmit').click(function(event) {  
  12.                 event.preventDefault();  
  13.                 alert("Hello");  
  14.             });  
  15.         });  
  16.     });  
  17. </script>

Let's focus on Ajax:

AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without reloading the whole page. It is a technique for creating fast and dynamic web pages.

In .NET, we can call server side code using two ways:

  1. ASP .NET AJAX
  2. jQuery AJAX

In this article we will focus on JQuery Ajax.

$.ajax () Method:

JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:

  • $.ajax() Performs an async AJAX request.
  • $.get() Loads data from a server using an AJAX HTTP GET request.
  • $.post() Loads data from a server using an AJAX HTTP POST request.

To know more click.

$.ajax () Method Configuration option:

Options that we use:

  • async:
  • type:
  • url:
  • data:
  • datatype:
  • success:
  • error:

Let’s have details overview:

async

Set to false if the request should be sent synchronously. Defaults to true.

Note that if you set this option to false, your request will block execution of other code until the response is received.

Example:

  1. async: false,

type

This is type of HTTP Request and accepts a valid HTTP verb.

The type of the request, "POST" or "GET" defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all the web browsers.

Example:

  1. type: "POST",

url

The URL for the request.

Example:

  1. url: "/Home/JqAJAX",

data

The data to be sent to the server. This can either be an object or a query string.

Example:

  1. data: JSON.stringify(model_data),

dataType

The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified.

Accepted values are text, xml, json, script, html jsonp.

Example:

  1. dataType: "json",

contentType

This is the content type of the request you are making. The default is 'application/x-www-form-urlencoded'.

Example:

  1. contentType: 'application/json; charset=utf-8',

success

A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the DataType was JSON), as well as the text status of the request and the raw request object.

  1. Success: function (result) {  
  2.    $('#result').html(result);  
  3. }

error

A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.

  1. error: function (result) {  
  2.    alert('Error occured!!');  
  3. },

Let’s Post Values using JQuey,Ajax:

We often use the jQuery Ajax method in ASP.NET Razor Web Pages. Here is a sample code:

  1. <input type="submit" id="btnSubmit" value="Add Student" />  
  2. <script type="text/javascript">  
  3.     $(document).ready(function() {  
  4.         $(function() {  
  5.             $('#btnSubmit').click(function(event) {  
  6.                 event.preventDefault();  
  7.                 var Student = {  
  8.                     ID: '10001',  
  9.                     Name: 'Shashangka',  
  10.                     Age: 31  
  11.                 };  
  12.                 $.ajax({  
  13.                     type: "POST",  
  14.                     url: "/Home/JqAJAX",  
  15.                     data: JSON.stringify(Student),  
  16.                     dataType: "json"  
  17.                     contentType: 'application/json; charset=utf-8',  
  18.                     success: function(data) {  
  19.                         alert(data.msg);  
  20.                     },  
  21.                     error: function() {  
  22.                         alert("Error occured!!")  
  23.                     }  
  24.                 });  
  25.             });  
  26.         });  
  27.     });  
  28. </script>

Controller Action:

  1. // GET: Home/JqAJAX  
  2. [HttpPost]  
  3. public ActionResult JqAJAX(Student st) {  
  4.     try {  
  5.         return Json(new {  
  6.             msg = "Successfully added " + st.Name  
  7.         });  
  8.     } catch (Exception ex) {  
  9.         throw ex;  
  10.     }  
  11. }

Posting JSON

JSON is a data interchange format where values are converted to a string. The recommended way to create JSON is include the JSON.stringify method. In this case we have defined:

  1. JSON.stringify(Student)

And the data type set to:

  1. datatype: "json"

And the content type set to application/json

  1. contentType: 'application/json; charset=utf-8'

Syntax:

JSON.stringify(value[, replacer[, space]])

Post Script:

  1. var Student = {  
  2.     ID: '10001',  
  3.     Name: 'Shashangka',  
  4.     Age: 31  
  5. };  
  6. $.ajax({  
  7.     type: "POST",  
  8.     url: "/Home/JqAJAX",  
  9.     data: JSON.stringify(Student),  
  10.     contentType: 'application/json; charset=utf-8',  
  11.     success: function(data) {  
  12.         alert(data.msg);  
  13.     },  
  14.     error: function() {  
  15.         alert("Error occured!!")  
  16.     }  
  17. });

Controller Action:

  1. // GET: Home/JqAJAX  
  2. [HttpPost]  
  3. public ActionResult JqAJAX(Student st) {  
  4.     try {  
  5.         return Json(new {  
  6.             msg = "Successfully added " + st.Name  
  7.         });  
  8.     } catch (Exception ex) {  
  9.         throw ex;  
  10.     }  
  11. }

JSON Response Result:

Sent data format:
{"ID":"10001","Name":"Shashangka","Age":31}
Received Data format:
{"msg":"Successfully added Shashangka"}


Let’s Post JavaScript Objects:

To send JavaScript Objects we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

  1. data: Student

And the datatype set to:

  1. datatype: "html"

And the content type set to default.

  1. contentType: 'application/x-www-form-urlencoded'

Post Script:

  1. var Student = {  
  2.     ID: '10001',  
  3.     Name: 'Shashangka',  
  4.     Age: 31  
  5. };  
  6. $.ajax({  
  7.     type: "POST",  
  8.     url: "/Home/JqAJAX",  
  9.     data: Student,  
  10.     contentType: 'application/x-www-form-urlencoded',  
  11.     datatype: "html",  
  12.     success: function(data) {  
  13.         alert(data.msg);  
  14.     },  
  15.     error: function() {  
  16.         alert("Error occured!!")  
  17.     }  
  18. });

Controller Action:

  1. // GET: Home/JqAJAX  
  2. [HttpPost]  
  3. public ActionResult JqAJAX(Student st) {  
  4.     try {  
  5.         return Json(new {  
  6.             msg = "Successfully added " + st.Name  
  7.         });  
  8.     } catch (Exception ex) {  
  9.         throw ex;  
  10.     }  

JavaScript Objects Response Result:

Sent data format:
ID=10001&Name=Shashangka&Age=31
Received Data format:
{"msg":"Successfully added Shashangka"}


Let’s Post JavaScript Arrays:

To send Array we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

  1. data: Student

And the datatype set to:

  1. datatype: "html"

And the content type set to default

  1. contentType: 'application/x-www-form-urlencoded'

Post Script:

  1. var ID = ["Shashangka""Shekhar""Mandal"];  
  2.   
  3. $.ajax({  
  4.     type: "POST",  
  5.     url: "/Home/JqAJAX",  
  6.     data: {  
  7.         values: ID  
  8.     },  
  9.     datatype: "html",  
  10.     contentType: 'application/x-www-form-urlencoded',  
  11.     success: function(data) {  
  12.         alert(data.msg);  
  13.     },  
  14.     error: function() {  
  15.         alert("Error occured!!")  
  16.     }  
  17. });

Controller Action:

  1. // GET: Home/JqAJAX  
  2. [HttpPost]  
  3. public ActionResult JqAJAX(string[] values) {  
  4.     try {  
  5.         return Json(new {  
  6.             msg = String.Format("Fist Name: {0}", values[0])  
  7.         });  
  8.     } catch (Exception ex) {  
  9.         throw ex;  
  10.     }  
  11. }

Array Response Result:

Sent data format:
values[]=Shashangka&values[]=Shekhar&values[]=Mandal
Received Data format:
{"msg":"Fist Name: Shashangka"}


Hope this will help to understand different datatypes and Ajax posting. Thanks!