Click here to Skip to main content
13,198,325 members (57,708 online)
Click here to Skip to main content
Articles » Web Development » ASP.NET » Samples » Revisions
Add your own
alternative version


115 bookmarked
Posted 5 Apr 2011

Refreshing content of the table using Ajax in ASP.NET MVC (jQuery DataTables and ASP.NET MVC integration - Part III)

, 26 Feb 2012
Rate this:
Please Sign up or sign in to vote.
This article shows how you can refresh content of the table in ASP.NET MVC using the jQuery DataTables plug-in.
This is an old version of the currently published article.

Table of content

  1. Introduction
  2. Background
  3. Using the code
    1. Model
    2. View
    3. Controller
  4. Summary


In this article I will show how you can refresh a HTML table content via Ajax. If you are using regular HTML tables reloading table is not too complicated task. All you need to do is to send some Ajax request to the server-side page, take the response from the server and put it in the table. I believe that this is something that you have done lot of times. There is a simple JQuery code that can do this:

$("table#employees tbody").load("TableContent.aspx");

This call will send Ajax call to the server-side page TableContent.aspx, read response that TableContent.aspx provides, and put it into the body of the table. In the TableContent.aspx page, you will need to return a valid HTML representing the set of rows that will be placed in the table.

This works fine if you have a simple table where you can replace content with response from server. However, if you have some advanced functionalities such as pagination, sorting, filtering this migh gets more complicated. When you send request to the server you will need to include information about the current page and table state, and make sure that you have loaded proper content, selected correct page number in the pagination etc. If you have more advanced tables, it would be better to use some existing component where the refresh functionality is already built-in.

My choice is JQuery DataTables plugin. With the JQuery DataTables plugin you can take a plain table and add pagination, filtering and sorting using the single JavaScript line of code:

var oEmployeesTable = $('table#employees').dataTable(); 

In this example is taken a plain HTML table with id "employees" and DataTables plugin is applied to the table. This call will add pagination, sorting, and filtering on the table.

You can also easily create fully AJAXified table using slightly different call:

var oEmployeesTable = $('table#employees').dataTable({
                                                       "bServerSide": true,
                                                       "sAjaxSource": "DataContent.aspx"

In this case are set two parameters specifying that information will be taken not from the HTML but from the server-side page DataContent.aspx.

If you use DataTables to refresh the table content, you will need to execute a single line of JavaScript code:


This call will refresh the table content. In this article I will show how you can implement refresh functionality in the ASP.NET MVC application.


JQuery DataTables plugin is an excellent JQuery library that enables you to create fully AJAXified tables with a minimal effort. To create AJAXified table with JQuery DataTables plugin you will need to implement following elements:

  1. Put an empty table in the HTML of the page. This empty table will define structure of the table (e.g. columns, styles, etc). The table should have only heading in the THEAD element, empty body, and optional footer in the TFOOT element. Rows in the table are not required because they will be loaded via Ajax call.
  2. Create some server-side page that will provide rows to the table when it is called via Ajax. in this article will be implemented ASP.NET MVC controller that will provide data rows to the table.
  3. Initiate JQuery DataTables plugin to load table content from the controller.

As an result, instead of the empty table you will get fully AJAXified table where JQuery DataTables has automatically added pagination, sorting by table headings, and filtering by keyword. Example of the table is shown on the following figure:


As you can see, JQuery DataTables plugin has taken a plain table with no content, populated it with rows via Ajax call, and added elements for sorting, filtering and pagination. You will see in the following sections that only thing that is needed are few lines of JavaScript code to initialize this table, and convert it to the fully functional AJAXified table.

You can find detailed instruction about the integration of JQuery DataTables plugin with the ASP.NET MVC controller in the jQuery DataTables and ASP.NET MVC Integration - Part I article.

Once you implement controller and initialize JQuery DataTables plugin, it will handle complete interaction with the user. Each time user change state of the table (e.g. change page using pagination, sort rows by column, or perform some search) DataTables plugin will send information to the controller and refresh the content of the table.

However, in some cases you will need to refresh the table content manually. Refreshing table content is common requirement in many applications - some example are:

  1. You might want to add refresh button that enables user to refresh the data displayed in the table.
  2. You might want to implement some periodical refresh of table content to provide the latest data to user (e.g. some live scores implementation).
  3. You might want to implement some kind of AJAXified search where user enters search criterion in the form and you want to refresh data in the table without refreshing whole page.
  4. You might want to add some master table or drop-down so when user select some value in the table or dropdown, you might want to refresh dependent table.
  5. You might want to add some filter to the table where user will type some text or select some value in the dropdown list, so you will need to refresh the table content to match filter.

To implement these scenarios you will need to refresh DataTables content. Goal of this article is to show how you can do it with API provided by JQuery DataTables plugin.

This is a third article in the series explaining how the jQuery DataTables plugin can be integrated into the ASP.NET MVC web application. If you are not familiar with the integration of the DataTables plug-in with ASP.NET MVC server-side code, you might want to read the first article in this series before you proceed.

Using the code

For illustrative purposes, we'll use a simple ASP.NET MVC web application to list the employees. The first thing you need to do is to create a standard ASP.NET Model-View-Controller structure. There are three steps required for this setup:

  1. Creating the model classes that represent a data structure to be shown.
  2. Creating the controller class that will react on the user events.
  3. Creating the view that will render data and create the HTML code that is sent to the browser window.

Also, you will need to include some JavaScript components in your project. The following JavaScript components need to be downloaded:

  1. jQuery library v1.4.4., containing the standard classes used by the DataTables plug-in.
  2. jQuery DataTables plug-in v1.7.5., including the optional DataTables CSS style-sheets used for applying the default styles on the page.

These files should be stored in the local file system and included in the HTML page that is rendered on the client. An example of usage of these files is explained below.


Two classes that contain information about companies and employees need to be added in the example. The classes are shown in the following listing:

public class Company
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Town { get; set; }
public class Employee
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public int CompanyID { get; set; }

The employees are connected to the companies via the CompanyID property. These classes will be used to show information on the page.


The view is used to render data on the server-side and to send HTML code to the browser. There's one layout page that is used to include all the necessary CSS and JavaScript files that are used on the page. This layout page is shown below:

<!DOCTYPE html>
        <title>Refreshing table content using a JQuery DataTables plugin</title>
        <link href="@Url.Content("~/Content/dataTables/demo_page.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/dataTables/demo_table.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/dataTables/demo_table_jui.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" media="all" />
        <link href="@Url.Content("~/Content/themes/smoothness/jquery-ui-1.7.2.custom.css")"rel="stylesheet" type="text/css" media="all" />
        <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.dataTables.min.js")" type="text/javascript"></script>
        @RenderSection("head", required: false)
    <body id="dt_example">
        <div id="container">

The layout page has two sections that can be populated on the page:

  1. head section where the JavaScript calls from the page will be injected,
  2. body section that enables the page that uses this layout page to inject code to the page that will be shown on the page.
In the following sections I will show few implementations of the pages that uses this layout page and refresh the table content.

Case 1 - Adding "Refresh" button

In the first example I will show how you can add Refresh button that will reload a content of the table when user press it. Example is shown on the following figure:


As described above we would need one empty table that holds table data and one refresh button. Body of the page is shown in the following listing:

<button id="Refresh" type="button">Refresh<button/>

<table id="employees" class="display">

Once we have prepared static HTML, we would need to initialize DataTables plugin, and attach click handler to the refresh button that will redraw table. Example of code is shown in the following listing.

@section head{
    <script language="javascript" type="text/javascript">
    $(document).ready(function () {

        var oEmployeesTable = $('#employees').dataTable({
            "bJQueryUI": true,
            "bServerSide": true,
            "sAjaxSource": "MasterDetailsAjaxHandler"

        $("#Refresh").click(function (e) {

This code should be placed in the head section of the view. The first statement in the document ready function applies DataTables plugin on the employees table, specified that it will work in the server-side mode (meaning that on each user action plugin will ask server-side page to provide new data that should be displayed), defines that URL that will be called via Ajax call is MasterDetailsAjaxHandler - this is a path of the controller that will provide content of the table. bJQueryUI flag is not mandatory - it is just used to apply JQuery UI styles to the table.

When table is initialized, in the code is added click handler for the refresh button that will draw content of the table. On each draw call, DataTables plugin will call server-side page again, and take the new set of data which will be loaded in the table body.

Controller that provides content is described in the section controller.

Case 2 - Refreshing table content periodically

If you do not want to force user to refresh the table, you can add function that will be periodically called to refresh the table. Code is very similar to the code shown in the case 1. The only difference is that refresh button is not needed and instead of te click handler is used set interval function as the one shown in the following listing:

@section head{
<script language="javascript" type="text/javascript">

    var oEmployeesTable = null;
    function refresh() {
        if (oEmployeesTable != null)
    setInterval("refresh()", 1000);

    $(document).ready(function () {
        oEmployeesTable = $('#employees').dataTable({
            "bJQueryUI": true,
            "bServerSide": true,
            "sAjaxSource": "/Home/MasterDetailsAjaxHandler"

In the global scope are defined references to the employees table, function that refresh table, and timer that calls refresh function each second. Then, in the document ready handler employees table is initialized with DataTables plugin and global reference is set.

As an result this table will be automatically reloaded each second. Trace of the Ajax calls that are sent to the server are shown on the figure below:


Note that reference to the employees table, function and interval call are placed in the global scope and not in the body of the document ready handler, because these functions references will be lost once the document ready handler finished.

Case 3 - Refreshing table content when parent row is selected

In this example I will shown how you can refresh content of the dependent table (employees) when some company is selected in the master table. In this case we will have two tables - one parent table containing the list of companies and the other child table containing the list of employees. Example of that kind of page is shown in the following figure:


When user selects the company in the master table, in the child table will be shown employees that belong to this company. The body of the page is shown in the following listing:

<div id="demo">
    <table id="companies" class="display">
                <th>Company name</th>
            <tr id="0" class="masterlink">
                <td>Emkay Entertainments</td>
                <td>Nobel House, Regent Centre</td>
            <tr id="1" class="masterlink">
                <td>The Empire</td>
                <td>Milton Keynes Leisure Plaza</td>
            <tr id="2" class="masterlink">
                <td>Asadul Ltd</td>
            <tr id="3" class="masterlink">
                <td>Ashley Mark Publishing Company</td>
                <td>1-2 Vance Court</td>
                <td>Tyne &amp; Wear</td>
            <tr id="4" class="masterlink">
                <td>MuchMoreMusic Studios</td>
                <td>Unit 29</td>
            <tr id="5" class="masterlink">
                <td>Audio Records Studios</td>
                <td>Oxford Street</td>

    <table id="employees" class="display">

The first table with companies contains a list of five companies, and the employees table is empty. The employees table will be populated with AJAX JavaScript calls. Each row in the companies table contains the ID of the company - this information will be used to load the employees for the selected company.

The head section holds the JavaScript code that initializes and connects these two tables. The JavaScript initialization code is shown in the following listing:

<script language="javascript" type="text/javascript">
    $(document).ready(function () {

        /* Initialize master table - optionally */
        var oCompaniesTable = $('#companies').dataTable({ "bJQueryUI": true });
        /* Highlight selected row - optionally */
        $("#companies tbody").click(function (event) {
            $(oCompaniesTable.fnSettings().aoData).each(function () {

        var MasterRecordID = null;

        var oEmployeesTable = $('#employees').dataTable({
            "sScrollY": "100px",
            "bJQueryUI": true,
            "bServerSide": true,
            "sAjaxSource": "MasterDetailsAjaxHandler",
            "bProcessing": true,
            "fnServerData": function (sSource, aoData, fnCallback) {
                aoData.push({ "name": "CompanyID", "value": MasterRecordID });
                $.getJSON(sSource, aoData, function (json) {

        $(".masterlink").click(function (e) {
            MasterRecordID = $(this).attr("id");

The first two statements are optional. The first statement initializes the companies table with the jQuery DataTables plug-in in order to add pagination, filtering, and sorting functionality (this is not required for the parent-child relationship between the tables because the parent table can be a plain table). The second statement adds the row_selected class on the selected row in the parent table. This is also not required, but it's useful to highlight a company whose employees are shown in the child table.

A local variable MasterRecordID is used to hold the ID of the currently selected company. The fourth statement initializes the child employees table. Most of the settings are optional and do not affect the parent-child configuration because the only relevant statements in the initialization are:

  1. Server-side processing configuration implemented using the bServerSide and sAjaxSource parameters,
  2. fnServerData method used to inject the ID of the selected company into the AJAX call sent to the server-side. This method is used to add the additional parameter called CompanyID with the value of the MasterRecordID variable to the AJAX call sent to the server-side.

The last statement attaches the event handler which populates the ID of the selected row and forces the redraw of the child table on each click on a row in the parent table. Redrawing of the table sends an AJAX request to the server-side and updates the table with the employee records that belong to the selected company.

Case 4 - Refeshing table when form is posted

Common scenario when you might need to reload table is then you post some form content via Ajax, and you want to reload the table to refresh the rows. As an example, you might add some add form in the page, and when new item is succesfully added you might want to reload the table content. Example of that kind of form is shown on the following figure.


In order to create that kind of functionality we would need to add one button and one dialog to the view. View body looks like the following HTML code:

<div id="dialog" title="Add new item">
    <label for="name">Title</label>
    <input type="text" id="name" name="name" value="" />
    <button type="button" id="save">Save</button>
 <button id="add">Add</button>

     <table id="employees" class="display">

One dialog is added in HTML where are placed text input for the new item and save button. Also one button that is used to open dialog is added above the table. Table that is enhanced with DataTables plugin is same as in the previous cases.

Now we would need to refresh the table after the save button posts request to the server-side. In this case, we would need to call function fnDraw in the success handler of the Ajax call. Example of that kind of JavaScript code is shown in the folowing listing:

var oEmployeesTable = $('#employees').dataTable({
            "bJQueryUI": true,
            "bServerSide": true,
            "sAjaxSource": "/Home/MasterDetailsAjaxHandler"

        $("#dialog").dialog({ autoOpen: false });
        $("#add").click(function (e) {

        $("#save").click(function (e) {
                            url: "/Home/AddItem",
                            data: {
                                name: function(){$("#name").val();}
                            success: function () {

First part is a standard initialization of DataTable as in the previous examples. Then dialog is initialized(it is not automatically opened), on the add button is added handler that opens dialog, and on the save button is aded handler that posts Ajax request to the server-side page and send name that is entered. In the success handler of the Ajax call dialog is closed and table is redrawn.

As an result each time you post the form you will see that table is reloded.

Case 5 - Filteirng using the form elements

Implementation of other cases of usage are similar the the three approaches described above. You can easily add some select dropdown, check boxes or even the entire form that will refresh the table content.

All you will need to do is to attach event handler that will call fnDraw function and inject parameters you want to send to the controller via Ajax call in the fnServerData settings in the initialization. When the fnDraw is called, DataTables plugin will send new Ajax request, pass parameters defined in the fnServerData, accept results, and put them in the table. therefore i will not show implementaitons of other cases because they are very similar.

If you want to refresh the using the form elements that are directly related to the columns in the table there is an easier option. You can use JQuery DataTables ColumnFilter add-on that can add form filters to the DataTable. You can see how this form filter works if you add the filters in the columns or in the separate form. This filter can be applied either on the row data that are already populated in the table or on the AJAXified table. With this plugin you do not need to implement event handlers and Ajax request. All you need to do is to apply column filter plugin on the DataTables plugin configured in the server side mode. Example of the code that initializes columnfilter pluign with DataTables in the server-side processing mode is shown in the following listing:

            "bJQueryUI": true,
            "bServerSide": true,
            "sAjaxSource": "MasterDetailsAjaxHandler"
            aoColumns: [ { type: "select"},
                     { type: "text" },
                     { type: "text" },
                     { type: "text" }

This example add one select list for filtering by first column and text boxes for filtering by other columns. If DataTables plugin is initialized in the server-side mode, filters will be also sent to the server-side via Ajax calls. You can see more details about the column filter configuration on the JQuery DataTables ColumnFilter site.

The last required part of the example is a controller that will handle the requests.


The controller handles the request sent from the browser and provides view/data that will be shown in the browser. Here, the controller has two methods that handle a request:

  1. Load method that returns the view page when the page is loaded,
  2. Employees AJAX handler that returns the employees when JQuery DataTables sends the Ajax request. This action will return employees data when JQuery DataTables plugin wants to refresh the content, therefore, it should accept standard parameters (current page, number of items per page, etc) that defines current view state of the table. However, to support refreshing table for selected company (case 3 above) in this controller action is added company id parameter that will be used to additionally filter employees by company.

The first controller method is fairly simple. This method just returns the view that will be shown in the browser, as shown in the following listing:

public class HomeController : Controller
    public ActionResult Index()
            return View();

The second controller method is crucial - it returns the employees for the employees table. This method is shown in the following listing:

public class HomeController : Controller
    public ActionResult MasterDetailsAjaxHandler(
             JQueryDataTableParamModel param, int? CompanyID)

        var employees = DataRepository.GetEmployees();

        //"Business logic" method that filters employees by the employer id
        var companyEmployees = (from e in employees
                                where (CompanyID == null || e.CompanyID == CompanyID)
                                select e).ToList();

        //UI processing logic that filter company employees by name and paginates them
        var filteredEmployees = (from e in companyEmployees
                                 where (param.sSearch == null || 
                                 select e).ToList();
        var result = from emp in filteredEmployees.Skip(
                     select new[] { Convert.ToString(emp.EmployeeID), 
                     emp.Name, emp.Position };

        return Json(new
            sEcho = param.sEcho,
            iTotalRecords = companyEmployees.Count,
            iTotalDisplayRecords = filteredEmployees.Count,
            aaData = result

The name of the method must match the sAjaxSource parameter set in the employees data table. This method accepts an object that encapsulates the parameters sent from the DataTables plug-in (current page, sort direction, number of items that should be displayed per page, etc.) More details about the server side processing parameters can be found in the first article in this series. Besides this parameter, an additional parameter called CompanyID is added in the method signature. This parameters is relevant only for case three and it is used to filter employees by the selected company id. The name of this parameter must match the name of the parameter that is added in the fnServerData function in the case 3. The other code in the body of the method just filters the employee data and returns it in JSON format as it is expected by the jQuery DataTables plug-in. More details about the server-side configuration can be found in the first article in this series.


This article shows how you can easily reload table content in ASP.NET MVC using the jQuery DataTables plug-in. Minimal code is required on the client-side, and on the server-side we need standard processing functions. This plug-in allows you to create an effective, AJAXified, Web 2.0 interface with minimal effort and straightforward implementation guidelines. You can download the example project implemented in ASP.NET MVC here.

You might also be interested in the other articles in this series showing:

  1. How to implement server-side processing in ASP.NET MVC with the jQuery DataTables plug-in
  2. How to implement a fully editable table in ASP.NET MVC with jQuery DataTables and several jQuery plug-ins that enable complete data management functionality.

I hope that these articles would help you while implementing ASP.NET MVC applications.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jovan Popovic
Program Manager Microsoft
Serbia Serbia
Graduated from Faculty of Electrical Engineering, Department of Computer Techniques and Informatics, University of Belgrade, Serbia.
Currently working in Microsoft as Program Manager on SQL Server product.
Member of JQuery community - created few popular plugins (four popular JQuery DataTables add-ins and loadJSON template engine).
Interests: Web and databases, Software engineering process(estimation and standardization), mobile and business intelligence platforms.

You may also be interested in...

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.
GeneralMy vote of 5 Pin
CuongPuyol23-Jun-15 23:56
memberCuongPuyol23-Jun-15 23:56 
GeneralMy vote of 5 Pin
dr.samuel.john31-Oct-14 19:34
memberdr.samuel.john31-Oct-14 19:34 
QuestionHow to select the row Pin
ebevictor29-Sep-14 21:46
memberebevictor29-Sep-14 21:46 
AnswerRe: How to select the row Pin
Member 1319738712-May-17 21:24
memberMember 1319738712-May-17 21:24 
GeneralVery good tutorial! Pin
Member 1039974412-May-14 3:26
memberMember 1039974412-May-14 3:26 
QuestionCase 3 ! Pin
Member 1017890713-Mar-14 12:35
memberMember 1017890713-Mar-14 12:35 
Questionplz help Pin
Member 454743020-Oct-13 7:09
memberMember 454743020-Oct-13 7:09 
QuestionCase 3 doesnt't work Pin
Member 97134734-May-13 0:01
memberMember 97134734-May-13 0:01 
AnswerRe: Case 3 doesnt't work Pin
Liutsko24-May-16 0:26
memberLiutsko24-May-16 0:26 
QuestionKeep pagination/sorting/filtering settings Pin
_koen_28-Apr-13 20:56
member_koen_28-Apr-13 20:56 
Questionpassing a array using ajax from view page to cotroller Pin
abusalehrajib21-Mar-13 2:51
memberabusalehrajib21-Mar-13 2:51 
GeneralMy vote of 5 Pin
Abinash Bishoyi27-Feb-13 0:48
memberAbinash Bishoyi27-Feb-13 0:48 
Questionhow to create a new row in mvc Pin
raja.mstech31-Jan-13 19:37
memberraja.mstech31-Jan-13 19:37 
QuestionHTML Helper to create Table with datatables plugin Pin
Rajagcha8-Aug-12 8:43
memberRajagcha8-Aug-12 8:43 
Bugajax.cshtml not working Pin
samthec11-May-12 4:47
membersamthec11-May-12 4:47 
GeneralMy vote of 5 Pin
Anurag Gandhi21-Apr-12 9:26
memberAnurag Gandhi21-Apr-12 9:26 
GeneralMy vote of 5 Pin
pothiq26-Feb-12 19:21
memberpothiq26-Feb-12 19:21 
GeneralMy vote of 5 Pin
Mahmud Hasan26-Feb-12 16:43
memberMahmud Hasan26-Feb-12 16:43 
QuestionGreat Article Pin
zyck26-Feb-12 3:39
memberzyck26-Feb-12 3:39 
GeneralMy vote of 5 Pin
Greg Sipes22-Feb-12 10:54
memberGreg Sipes22-Feb-12 10:54 
GeneralMy vote of 5 Pin
Prasanta_Prince17-Apr-11 7:33
memberPrasanta_Prince17-Apr-11 7:33 
GeneralOdlicno 5 Pin
Slobodan12-Apr-11 11:02
memberSlobodan12-Apr-11 11:02 
GeneralRe: Odlicno 5 Pin
Jovan Popovic13-Apr-11 21:25
memberJovan Popovic13-Apr-11 21:25 
GeneralMy vote of 5 Pin
Arlen Navasartian8-Apr-11 4:34
memberArlen Navasartian8-Apr-11 4:34 
GeneralGood Pin
Sunasara Imdadhusen6-Apr-11 23:37
memberSunasara Imdadhusen6-Apr-11 23:37 
GeneralError: Stuck on 'Processing' Pin
vkuttyp6-Apr-11 4:34
membervkuttyp6-Apr-11 4:34 
GeneralRe: Error: Stuck on 'Processing' Pin
Jovan Popovic6-Apr-11 5:02
memberJovan Popovic6-Apr-11 5:02 
GeneralRe: Error: Stuck on 'Processing' Pin
vkuttyp6-Apr-11 11:45
membervkuttyp6-Apr-11 11:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171020.1 | Last Updated 26 Feb 2012
Article Copyright 2011 by Jovan Popovic
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid