Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Client side repeater using JQuery and ASP.NET MVC

4.25/5 (3 votes)
5 May 2010CPOL3 min read 32.9K  
Introduction...

Introduction


In my recent project I had a requirement to render grid in client side. My first concern is to use YUI datatable or JQuery Grid. Of course they are awesome tools but I want to make it simple. I don't want additional dependencies on project. So I decided to create my own grid. Thanks to JQuery, It makes programmers life easier. It's rich API help us to do difficult things with a few lines of code.

How our JQuery Grid Works


Here is the complete code for the JQuery grid. The grid constructor accepts the name of the grid, an array of column names, css class name of item template element and a url to retrieve data as JSON. JSON is my favorite data interchange format in javascript because it is lightweight than XML and there are lot of functions to handle JSON in JQuery. The grid is capable to load itself by retrieving data from url parameter. The grid class have a LoadData function which retrieve the data using getJSON JQuery function. Here is the core idea behind how JGrid works.

1. Save all input parameters on variables.

2. Keep a copy of item template element in a variable. This is using to get a clone copy of item template every time a new row created in the grid.

3. Retrieve the json array from the given url.

4. Clear all contents in the grid element. This is to clear the existing contents while we reload the grid from client side.

5. Loop through the resultant json array.

6. Pick one row from json array and loop through column array.

7. Replace all the #<Column Name> from item template with the value of corresponding field name in json array.

8. Append the modified item template element to the grid element.

9. Restore a clone copy of item template into the item template variable.

10. Repeat from step 5 until the loop reads all data from json array.

JavaScript
function JGrid(grid_name, columns, template_class, url) {

    //Step 1
    JGrid.grid = $("#" + grid_name);
    JGrid.item_template = $("." + template_class);
    JGrid.Url = url;

    //Step 2
    JGrid.html = JGrid.item_template.clone();

    this.LoadData = function () {

        //Step 3
        $.getJSON(JGrid.Url, function (data) {

            //Step 4
            $("." + template_class).remove();

            //Step 5
            $.each(data, function (i, value) {

                //Step 6
                $.each(columns, function (j, column) {

                    //Step 7
                    JGrid.item_template.html(JGrid.item_template.html().replace('#' + column.column, eval('(value.' + column.column + ')')));
                });

                //Step 8
                JGrid.grid.append(JGrid.item_template);

                 //Step 9
                JGrid.item_template = JGrid.html.clone();
            });

        });//Step 10
    };
}


HTML Template


Here is the html tags to create a client side repeater. The table tag with the id "customers" is the container for all items. The tr with css class attribute "items" is the item template. The JGrid repeats the item template in the grid container. The JGrid identifies the item template element using the item template css class parameter. So you must be careful to name the css class. If it repeats elsewhere in the page, the result will be unpredictable. #<Column Name> identifies the columns in item template. The column name and JSON field name should be same.

HTML
<table id="customers" border="0" cellpadding="4" cellspacing="4" width="100%">
<tr>
<th style="width:10%">Id</th>
<th style="width:90%">Name</th>
</tr>
<tr class="items">
<td>#CustomerId</td>
<td>#CustomerName</td>
</tr>
</table>


How to Render the Grid


Here it the javascript code to create grid. The first argument is the id of the grid element which is the container of item template. Second parameter is the column names used in the item template. The third parameter is name of the item template's css class attribute. Using this class name, JGrid identifies and get the item template element from the grid. The forth parameter is the url to get the data. The url must return a json result. The grid load with data only at the time of LoadData executed. If you want to reload the grid, just call the LoadData function.

JavaScript
<script type="text/javascript">
    var grid;
    $(function () {
        var columns = [{ column: "CustomerId" }, { column: "CustomerName" }];
        grid = new JGrid("customers", columns, "items", "/Home/GetCustomers");
        grid.LoadData();
    });
</script>


Server Side Coding


The GetCustomers function is pretty simple. It just create a list of customers and pass them as a json array. In this example our JGrid using the url of this function. The class JsonResult in ASP.NET MVC is capable to send json formatted content to response without additional coding. If you are using ASP.NET web forms, then you have to write additional code to generate json result.

C#
public class Customer
{
    public long CustomerId { get; set; }
    public string CustomerName { get; set; }
}

public JsonResult GetCustomers()
{
     List<Customer> customers = new List<Customer>();

     for (int i = 1; 10 >= i; i++)
     {
          customers.Add(new Customer() { CustomerId = i, CustomerName = string.Format("Customer {0}", i) });
     }

     return Json(customers);
}



References


ASP.NET AJAX And Client-Side Templates[^]

Using jQuery with Client-Side Data Binding Templates[^]

License

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