jTable.org

A JQuery plugin to create AJAX based CRUD tables.

Demos | Documentation | Discussion | Themes | Downloads | About
jTable on GitHub Github

Using jTable with ASP.NET Web Forms

Introduction

In this tutorial, I'll show how to use jTable with ASP.NET Web Forms. First, see completed jTable instance that will be developed:

I you haven't tried yet, please try to add a new record, to delete a record, to edit a record, to change current page and to sort the table by clicking column headers.

Creating ASPX page

Create a new ASP.NET web application project, download jTable and add all files to your project. Then create a new web form (say PagingAndSorting.aspx).

To be able to use jTable, we must include needed CSS and JavaScript files to our page as shown below:

<!-- jTable style file -->
<link href="/Scripts/jtable/themes/standard/blue/jtable_blue.css" rel="stylesheet" type="text/css" />

<!-- A helper library for JSON serialization -->
<script type="text/javascript" src="/Scripts/jtable/external/json2.js"></script>
<!-- Core jTable script file -->
<script type="text/javascript" src="/Scripts/jtable/jquery.jtable.js"></script>
<!-- ASP.NET Web Forms extension for jTable -->
<script type="text/javascript" src="/Scripts/jtable/extensions/jquery.jtable.aspnetpagemethods.js"></script>

We are adding two extra script files: json2.js is for JSON serialization, jquery.jtable.aspnetpagemethods.js is for using jTable with ASP.NET Page Methods. Script files must be included in the order above.

Client side (HTML and JavaScript)

HTML codes for jTable is very simple, just a div tag:

<div id="StudentTableContainer"></div>

jTable creates all table, forms and other stuffs. Let's see all JavaScript codes needed:

<script type="text/javascript">

    $(document).ready(function () {

        //Prepare jtable plugin
        $('#StudentTableContainer').jtable({
            title: 'The Student List',
            paging: true, //Enables paging
            pageSize: 10, //Actually this is not needed since default value is 10.
            sorting: true, //Enables sorting
            defaultSorting: 'Name ASC', //Optional. Default sorting on first load.
            actions: {
                listAction: '/PagingAndSorting.aspx/StudentList',
                createAction: '/PagingAndSorting.aspx/CreateStudent',
                updateAction: '/PagingAndSorting.aspx/UpdateStudent',
                deleteAction: '/PagingAndSorting.aspx/DeleteStudent'
            },
            fields: {
                StudentId: {
                    key: true,
                    create: false,
                    edit: false,
                    list: false
                },
                Name: {
                    title: 'Name',
                    width: '23%'
                },
                EmailAddress: {
                    title: 'Email address',
                    list: false
                },
                Password: {
                    title: 'User Password',
                    type: 'password',
                    list: false
                },
                Gender: {
                    title: 'Gender',
                    width: '13%',
                    options: { 'M': 'Male', 'F': 'Female' }
                },
                CityId: {
                    title: 'City',
                    width: '12%',
                    options: '/PagingAndSorting.aspx/GetCityOptions'
                },
                BirthDate: {
                    title: 'Birth date',
                    width: '15%',
                    type: 'date',
                    displayFormat: 'yy-mm-dd'
                },
                Education: {
                    title: 'Education',
                    list: false,
                    type: 'radiobutton',
                    options: { '1': 'Primary school', '2': 'High school', '3': 'University' }
                },
                About: {
                    title: 'About this person',
                    type: 'textarea',
                    list: false
                },
                IsActive: {
                    title: 'Status',
                    width: '12%',
                    type: 'checkbox',
                    values: { 'false': 'Passive', 'true': 'Active' },
                    defaultValue: 'true'
                },
                RecordDate: {
                    title: 'Record date',
                    width: '15%',
                    type: 'date',
                    displayFormat: 'dd.mm.yy',
                    create: false,
                    edit: false,
                    sorting: false //This column is not sortable!
                }
            }
        });

        //Load student list from server
        $('#StudentTableContainer').jtable('load');
    });

</script>

We first initialized jTable and called load method. You can see all options, events and methods on reference documentation.

Server side (ASP.NET code behind)

Student record

A record in the table above is represented by a Student object in the server side. Student class is defined as below:

public class Student
{
    public int StudentId { get; set; }

    public int CityId { get; set; }

    public string Name { get; set; }

    public string EmailAddress { get; set; }

    public string Password { get; set; }

    // "M" for mail, "F" for female.
    public string Gender { get; set; }

    public DateTime BirthDate { get; set; }

    public string About { get; set; }

    // 0: Unselected, 1: Primary school, 2: High school 3: University
    public int Education { get; set; }

    //true: Active, false: Passive
    public bool IsActive { get; set; }

    public DateTime RecordDate { get; set; }

    public Student()
    {
        RecordDate = DateTime.Now;
        Password = "123";
        About = "";
    }
}

A student lives in a city (Joined on CityId field). City is a simple class:

public class City
{
    public int CityId { get; set; }

    [Required]
    public string CityName { get; set; }
}

It's not needed to define such a class, but I defined it to be more object-oriented. We will use it to get city options while editing/creating/listing students.

Getting list from server

jTable calls listAction (defined in jTable initialization options) using AJAX to load records in the table when you call load method. In the sample, we defined listAction as '/PagingAndSorting.aspx/StudentList'. This is a Page method defined in PagingAndSorting.aspx as shown below:

[WebMethod(EnableSession = true)]
public static object StudentList(int jtStartIndex, int jtPageSize, string jtSorting)
{
    try
    {
        //Get data from database
        int studentCount = Repository.StudentRepository.GetStudentCount();
        List<Student> students = Repository.StudentRepository.GetStudents(jtStartIndex, jtPageSize, jtSorting);

        //Return result to jTable
        return new { Result = "OK", Records = students, TotalRecordCount = studentCount };
    }
    catch (Exception ex)
    {
        return new { Result = "ERROR", Message = ex.Message };
    }
}

A Page method is a static method that is marked with WebMethod attribute (EnableSession is an optional parameter). A Page method can be called by Javascript using AJAX. It gets and returns JSON objects. In the sample above, StudentList method does not get any argument and returns an anonymous object. Return value is used by jTable to show records.

In the sample, I used paging and sorting features of jTable. jTable sends paging and sorting parameters as parameters to the method (it also sends same values as query string arguments, so you can get as like HttpContext.Current.Request["jtStartIndex"] also.). Return value of method must contain: a Result string ("OK" or "ERROR"), Records array/list (a list of student records here) and TotalRecordCount (used for paging). If you don't use paging or sorting, you can must remove appropriate method arguments.

Note that Repositories here are classes to perform database operations. You can implement it in any technology (ADO.NET, Entity framework, NHibernate... etc.).

Getting City options

We defined a CityId field in the jTable initialization code. It has an option property that ensures to show a dropdown list in create/edit form. Value of this property was '/PagingAndSorting.aspx/GetCityOptions'. jTable uses this url to get all cities. This is a Page method defined in PagingAndSorting.aspx as shown below:

[WebMethod(EnableSession = true)]
public static object GetCityOptions()
{
    try
    {
        var cities = Repository.CityRepository.GetAllCities().Select(c => new { DisplayText = c.CityName, Value = c.CityId });
        return new { Result = "OK", Options = cities };
    }
    catch (Exception ex)
    {
        return new { Result = "ERROR", Message = ex.Message };
    }
}
An option method must return Options property that contains an array of options. A member of this array can be any type of object which has DisplayText and Value properties.

Deleting a record

jTable calls deleteAction (defined in jTable initialization options) using AJAX to delete a record in server, when user deletes a row on the table. In the sample, we defined deleteAction as '/PagingAndSorting.aspx/DeleteStudent'. This is a Page method defined in PagingAndSorting.aspx as shown below:

[WebMethod(EnableSession = true)]
public static object DeleteStudent(int StudentId)
{
    try
    {
        Repository.StudentRepository.DeleteStudent(StudentId);
        return new { Result = "OK" };
    }
    catch (Exception ex)
    {
        return new { Result = "ERROR", Message = ex.Message };
    }
}

As you've seen, it's a simple method which gets StudentId to delete. Notice that StudentId argument is case-sensitive and must match with jTable field name. So, if you use studentId as the parameter name, it won't work.

Creating a new record

jTable calls createAction (defined in jTable initialization options) using AJAX to add a new record to server when user saves create new record form. In the sample, we defined createAction as '/PagingAndSorting.aspx/CreateStudent'. This is a Page method defined in PagingAndSorting.aspx as shown below:

[WebMethod(EnableSession = true)]
public static object CreateStudent(Student record)
{
    try
    {
        var addedStudent = Repository.StudentRepository.AddStudent(record);
        return new { Result = "OK", Record = addedStudent };
    }
    catch (Exception ex)
    {
        return new { Result = "ERROR", Message = ex.Message };
    }
}

Creating method is also very straightforward. It must return new created object to jTable. Note that, since this is a new record, StudentId of Student object is not set (0 as default). But returning Student object to jTable must has a valid StudentId. So, you must get StudentId after inserting database. jTable will use this Id in next operations on the record (update and delete).

Lastly, record parameter's name must be record. Otherwise, it does not work since jTable set it's name as record.

Updating a record

jTable calls updateAction (defined in jTable initialization options) using AJAX to update a record to server when user saves edit form for a record. In the sample, we defined updateAction as '/PagingAndSorting.aspx/UpdateStudent'. This is a Page method defined in PagingAndSorting.aspx as shown below:

[WebMethod(EnableSession = true)]
public static object UpdateStudent(Student record)
{
    try
    {
        Repository.StudentRepository.UpdateStudent(record);
        return new { Result = "OK" };
    }
    catch (Exception ex)
    {
        return new { Result = "ERROR", Message = ex.Message };
    }
}

Summary

In this tutorial, we developed a jTable with paging and sorting features enabled using ASP.NET Web Forms Page methods in the server side. jTable has direct support for Page Methods of ASP.NET Web Forms. You can see demos page for other examples.

Download

You can download codes from download page.

Advertisement: Professional startup template for ASP.NET MVC & AngularJs by creator of jTable!

ASP.NET Zero screenshot Based on metronic theme, includes pre-built pages like login, register, tenant, role, user, permission and setting management. Learn more...