Using AJAX In ASP.NET MVC

What is Ajax?

As we all know, AJAX means Asynchronous JavaScript and XML. It is a client-side script that communicates to and from a server/database without the need for a postback or a complete page refresh. The Ajax speeds up response time.

In other words, Ajax is the method of exchanging data with a server, and updating parts of a web page, without reloading the entire page.
 
Some of the Benefits of Ajax are
  • Callbacks
  • Making Asynchronous Calls
  • User-Friendly
  • Improve the speed, performance and usability of a web application
Implementation of Ajax can be done in two way in ASP.Net Application
  • using Update Panel and,
  • using jQuery
What Advances have Been Made to Ajax?

JavaScript is the client-side scripting language and XML is a mark-up language to define data. And we have, JSON(JavaScript Object Notation) as another mark-up language to define data as well. JSON is much easier to use with JavaScript than XML. After the combination of JavaScript and Ajax, the XML Web Services are being replaced by JSON Web Services.

Another major advance to JavaScript and Ajax is the JavaScript object library called jQuery, which is the free, open-source software. It is a wrapper for JavaScript. jQuery is used to write the JavaScript to navigate and manipulate a page and make asynchronous Ajax callbacks.

Hence, Ajax callbacks have become standard programming practices by using jQuery and JSON Web Services for designing and developing web applications.

Demonstration: Implementation of Ajax using jQuery

Step 1

Create a new Project and choose ASP.NET MVC web application.
 
Step 2

Just Ignore the built-in Models and Controllers and make your own model.

Here I am creating a model called "Students" having properties studentID, studentName and studentAddress as shown below,

 

Code Snippet
  1. public class Student  
  2.     {  
  3.         [Key]  
  4.         public int studentID { getset; }  
  5.         [Required]  
  6.         public string studentName { getset; }  
  7.         [Required]  
  8.         public string studentAddress { getset; }  
  9.     }  
Add "using System.ComponentModel.DataAnnotations;" Attributes to Validate Model Data and then build the project once.
 
Step 3

Let's create another model by inheriting the DbContext. It is a class that manages all the database operations, like database connection, and manages various entities of the Entity Model.

We can also say DbContext is a wrapper of ObjectContext. So, DbContext is a lightweight version of the ObjectContext and is exposes only the common features that are really required in programming.

Here I am creating a model called "StudentContext" as shown below,

 
Code Snippet
  1. public class StudentContext : DbContext  
  2.     {  
  3.         public DbSet<Student> Students { getset; }  
  4.     }  
Add "using System.Data.Entity;" that provides access to the core functionality of the entity framework.
 
Step 4

Now create a controller to written the code for inserting data into database, displaying data into view.
Here I am creating "Student" controller. Inside the Controller, I am creating an object of StudentContext for inserting and retrieving data from database. Also add the necessary namespace.

 

Code Snippet
  1. StudentContext context = new StudentContext();  
Step 5

Now I'm creating the action methods for Inserting and retrieving the data to/from the database.

Here I am creating an [HttpPost] action method "createStudent" for inserting the JSON-Formatted data to database. I am Using [HttpPost] attribute to Save/Post the data as below:
 
Code Snippet
  1. [HttpPost]  
  2.         public ActionResult createStudent(Student std)  
  3.         {  
  4.             context.Students.Add(std);  
  5.             context.SaveChanges();  
  6.             string message = "SUCCESS";  
  7.             return Json(new { Message = message, JsonRequestBehavior.AllowGet });  
  8.         }  
Similarly, I am also creating JSON method "getStudent" to retrieve data from database and returning raw JSON data to be consumed by JavaScript in view as shown below,

 

Code Snippet
  1. public JsonResult getStudent(string id)  
  2.         {  
  3.             List<Student>students = new List<Student>();  
  4.             students = context.Students.ToList();  
  5.             return Json(students, JsonRequestBehavior.AllowGet);  
  6.         }  
Step 6

Now add a view to display the data and data inserting field. Here, I am adding a view named "Index.cshtml". Then, write the HTML codes for making the data input field, submit button and also for displaying the data in same page. You can use bootstrap classes for designing. Here I am using bootstrap. My designing code is as below:
 
Code Snippet
  1. <div class="col-md-12">  
  2.     <div class="panel panel-primary">  
  3.         <div class="panel-heading">  
  4.             <h3 class="panel-title">Please enter the details below.</h3>  
  5.         </div>  
  6.         <div class="panel-body">  
  7.             <div class="form-group col-md-5">  
  8.                 <label>Student Name</label>  
  9.                 <input type="text" name="StudentName" id="StudentName" class="form-control" placeholder="Enter Student Name" required="" />  
  10.             </div>  
  11.             <div class="form-group col-md-5">  
  12.                 <label>Student Address</label>  
  13.                 <input type="text" name="StudentAddress" id="StudentAddress" class="form-control" placeholder="Enter Student Address" required="" />  
  14.             </div>  
  15.   
  16.             <div class="form-group col-md-1">  
  17.                 <div style="float: right; display:inline-block;">  
  18.                     <input class="btn btn-primary" name="submitButton" id="btnSave" value="Save" type="button">  
  19.                 </div>  
  20.             </div>  
  21.         </div>  
  22.     </div><hr />  
  23.     <table id="tblStudent" class="table table-bordered table-striped table-responsive table-hover">  
  24.         <thead>  
  25.             <tr>  
  26.                 <th align="left" class="productth">ID</th>  
  27.                 <th align="left" class="productth">Student Name</th>  
  28.                 <th align="left" class="productth">Student Address</th>  
  29.             </tr>  
  30.         </thead>  
  31.         <tbody></tbody>  
  32.     </table>  
  33. </div>  
We can simply use the bootstrap class and call jQuery functions in ASP.NET MVC because during the project creation it will by default added to project and also linked to the template.

Step 7

Now I will write the script for inserting the data as well as retrieving and displaying it to the view. Just after the HTML code finished add the script shown below,
  1. @section Scripts  
  2. {  
  3.     <script type="text/javascript">  
  4.     $(function () {  
  5.         LoadData();  
  6.         $("#btnSave").click(function () {  
  7.             //alert("");  
  8.             var std = {};  
  9.             std.studentName = $("#StudentName").val();  
  10.             std.studentAddress = $("#StudentAddress").val();  
  11.             $.ajax({  
  12.                 type: "POST",  
  13.                 url: '@Url.Action("createStudent")',  
  14.                 data: '{std: ' + JSON.stringify(std) + '}',  
  15.                 dataType: "json",  
  16.                 contentType: "application/json; charset=utf-8",  
  17.                 success: function () {  
  18.                    // alert("Data has been added successfully.");  
  19.                     LoadData();  
  20.                 },  
  21.                 error: function () {  
  22.                     alert("Error while inserting data");  
  23.                 }  
  24.             });  
  25.             return false;  
  26.         });  
  27.     });  
  28.       
  29.     function LoadData() {  
  30.         $("#tblStudent tbody tr").remove();  
  31.         $.ajax({  
  32.             type: 'POST',  
  33.             url: '@Url.Action("getStudent")',  
  34.             dataType: 'json',  
  35.             data: { id: '' },  
  36.             success: function (data) {  
  37.                 var items = '';  
  38.                 $.each(data, function (i, item) {  
  39.                     var rows = "<tr>"  
  40.                     + "<td class='prtoducttd'>" + item.studentID + "</td>"  
  41.                     + "<td class='prtoducttd'>" + item.studentName + "</td>"  
  42.                     + "<td class='prtoducttd'>" + item.studentAddress + "</td>"  
  43.                     + "</tr>";  
  44.                     $('#tblStudent tbody').append(rows);  
  45.                 });  
  46.             },  
  47.             error: function (ex) {  
  48.                 var r = jQuery.parseJSON(response.responseText);  
  49.                 alert("Message: " + r.Message);  
  50.                 alert("StackTrace: " + r.StackTrace);  
  51.                 alert("ExceptionType: " + r.ExceptionType);  
  52.             }  
  53.         });  
  54.         return false;  
  55.     }  
  56.     </script>  
  57. }  
We are using Ajax to refresh "tblStudent" so it refreshes only the particular table, rather than refreshing entire page. After clicking the "submitButton" the data from the input fields are taken in variable and redirected to action "createStudent" of "StudentController" to insert into the database. And, I have written a function "LoadData" to display the data from database to view continuously after inserting data. Inside "LoadData" function I am calling "getStudent" method which returns result in JSON and the JSON-Formatted data are presented in html by the underlying statements.
 
Step 8

Now, configure the Database connectionStrings in "web.config" file of the particular project as shown below,
  1. <connectionStrings>  
  2.     <add name="StudentContext" connectionString="Data Source=RAVI-KANDEL;Initial Catalog=Student;Integrated Security=True"  
  3.       providerName="System.Data.SqlClient" />  
  4.   </connectionStrings>   
In the above connectingString "StudentContext" is the name of class inherited from abstract Class "DbContext" in "StudentContext.cs" file. "RAVI-KANDEL" is the name of the Database Server and "Student" is the name of the Database. Change "RAVI-KANDEL" with your Database Server name. Finally, run your application and navigate to Student controller. Also you can configure "RouteConfig.cs" and set the controller to "Student" for direct navigation to the Student controller when loading the application.
 
You can add the records and can see added data in the table after the form-control as shown below,


Also, you can open the database server and see the data stored in database over there.
 
Please feel free to comment/feedback.
 
Happy Coding!
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now