C#/VB.Net: How to use JQuery to Bind Gridview with Json from Web Method (Add, Edit & Delete)

Written by Amos Lai

Download the sample project (C#) – 72.5 kb

Download the sample project (VB.Net) – 74.9 kb


Hands
Amos Lai
14 May 2018

C#/VB.Net: How to use JQuery to Bind Gridview with Json from Web Method (Add, Edit & Delete)

This article shows you how to use Jquery to bind Gridview control with Json from Web Method. We will use JQuery AJAX to call the [WebMethod] functions to get what we need. Inside these [Webmethod] functions, there will read and write the data from json file. Besides that, the Add, Edit and Delete functions are there for you to alter the students data. Any changes from this Gridview will be save into a jason file.

Hands

Step 1

Create an empty website project (ASP.NET).

Step 2

We need to install Newtonsoft.Json from NuGet. Look for 'References' from Solution Explorer and right click. Then go to 'Manage NuGet Packages...'. After that, go the 'Borwse' and search 'Newtonsoft' from the search bar. Once you found it, select 'Newtonsoft.Json' and install as shown below.

Hands

After the installation, you will see 'Newtonsoft.Json' in your References.

Hands

Step 3

We need to install JQuery to massage the Json data and display them in the Gridview. You can go to 'http://jquery.com/' and look for the version you and download it. If your Internet Explorer version 6 or 7, download JQuery version 1.x. Or else you can just download the latest version. after that, create a 'script' folder in your solution and place the Jquery file into this folder.

Hands

Step 4

In this demonstration, we will populate the Gridview with Json data from the json file. Create a folder called 'App_Data' then add in a json file called 'Students.json' into this folder as shown below.

Hands

Step 5

We need some data sample for this demonstration. Let's open the 'Students.json' file and then copy the code below and paste it into this file. And save it.

                                
[
  {
    "Stid": 0,
    "Name": "James",
    "Gender": "Male",
    "LocalStudent": true
  },
  {
    "Stid": 1,
    "Name": "Jennifer",
    "Gender": "Female",
    "LocalStudent": false
  },
  {
    "Stid": 2,
    "Name": "Daniel",
    "Gender": "Male",
    "LocalStudent": false
  },
  {
    "Stid": 3,
    "Name": "Sabina",
    "Gender": "Female",
    "LocalStudent": true
  },
  {
    "Stid": 4,
    "Name": "Bryan",
    "Gender": "Male",
    "LocalStudent": true
  },
  {
    "Stid": 5,
    "Name": "Leah",
    "Gender": "Female",
    "LocalStudent": false
  }
]
                                
                            

Step 6

Create a 'Default.aspx' file in your solution. Then reference the JQuery in the HTML <script> tag at the top of the page.

                                
<!DOCTYPE html>

<!--Add JQuery script-->
<script type="text/javascript" src="scripts/jquery-3.3.1.js"></script>
                                
                            

Step 7

Add Gridview Control into HTML <form> tag. Then change the Gridview's ID to 'gvStudent'.

                                
<body>
    <form id="form1" runat="server">
        <div>
            <!--Add Gridview and change the ID to 'gvStudent'-->
            <asp:GridView ID="gvStudent" runat="server">
            </asp:GridView>
        </div>
    </form>
</body>
                                
                            

Step 8

In HTML <body> tag, add in a onload attribute and call 'BindGridView()' function.

                                
<body onload="BindGridView()">
                                
                            

Step 9

Now is time to add some javascript functions. At the bottom of the HTML <script> tag that referencing JQuery, create another <script> tag. Then add the javascript functions such as Bind Gridview, add, edit and delete functions as shown below.

                                
<script type="text/javascript">

    function BindGridView() {

        $(document).ready(function () {

            //Leave the 1st row (header) and delete all others row from the Gridview
            $('#gvStudent tr').not($('#gvStudent tr:first-child')).remove();

            //Use Ajax to connect to the Web Service and retrieve the data from App_Data/Student.json file 
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/GetStudent',
                data: '{}',
                contentType: 'application/json',
                dataType: 'json',
                success: function (data) {

                    //Loop the data and create new rows to list out all the students detail.
                    for (var i = 0; i < data.d.length; i++) {
                        $('#gvStudent').append('<tr style="background-color:white">' +
                            '<td><span id="Stid' + data.d[i].Stid + '">' + data.d[i].Stid + '</span></td>' +
                            '<td><span id="Name' + data.d[i].Stid + '">' + data.d[i].Name + '</span>' + '<input hidden type="text" id="txtName' + data.d[i].Stid + '" value="' + data.d[i].Name + '"></td>' +
                            '<td><span id="Gender' + data.d[i].Stid + '">' + data.d[i].Gender + '</span>' + '<select hidden id="selGender' + data.d[i].Stid + '"><option value="Male">Male</option><option value="Female" ' + (data.d[i].Gender === 'Female' ? 'selected' : '') + '>Female</option></select></td>' +
                            '<td><input type="checkbox" id="chkLocalStudent' + data.d[i].Stid + '" disabled ' + (data.d[i].LocalStudent === true ? 'checked' : '') + '></input></td>' +
                            '<td><table><tr><td><input type="button" id="btnEdit' + data.d[i].Stid + '" onclick="EditStudent(this.id);" value="Edit"/></td><td><input type="button" id="btnDelete' + data.d[i].Stid + '" onclick="DeleteStudent(this.id);" value="Delete"></td></tr></table></td>' +
                            '</tr>');
                    }

                    //Create last row and add textbox, dropdownlist and radio buttons for purpose of adding new student.
                    $('#gvStudent').append('<tr style="background-color:Silver">' +
                        '<td></td>' +
                        '<td><input type="text" id="txtName"></input></td>' +
                        '<td><select id="selGender"><option selected>Please Select</option><option value="Male">Male</option><option value="Female">Female</option></select></td>' +
                        '<td><input id="rdIsLocal" type="radio" name="rdLocalStudent" value="Yes"/>Yes<input id="rdNotLocal" type="radio" name="rdLocalStudent" value="No"/>No</td>' +
                        '<td><input type="button" id="btnAdd" onclick="AddStudent();" value="Add Student"/>' +
                        '</tr>');
                },
                error: function (ex) {
                    alert(ex.responseText);
                }
            });
        });
    }

    function AddStudent() {

        $(document).ready(function () {

            //Textbox (Name) can not be emmptied
            if ($('#txtName').val() === '') {
                alert('Please enter the Name.');
                return;
            };
            //dropdownlist (Gender) can not be emptied
            if ($('#selGender option:selected').val() === 'Please Select') {
                alert('Please select the Gender.');
                return;
            }
            //Radio Button (Local Student) can not be emptied
            if ($('input[name="rdLocalStudent"]:checked').val() === undefined) {
                alert('Please check the Local Student.');
                return;
            }

            //Get ready the new values to pass into Web Service
            var strName = $('#txtName').val();
            var strGender = $('#selGender').val();
            var bolLocalStudent = $('input[name="rdLocalStudent"]:checked').val() === 'Yes' ? true : false;

            //Use Ajax to connect to the Web Service and add new data into App_Data/Student.json file 
            //and create new student unique ID then send it back to here.
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/AddStudent',
                data: '{"pName":"' + strName + '", "pGender":"' + strGender + '", "pLocalStudent":' + bolLocalStudent + '}',
                contentType: 'application/json',
                dataType: 'json',
                success: function (data) {

                    //Get the number of lines of the whole Gridview
                    var intNoOfLines = $('#gvStudent >tbody >tr').length;

                    //Find the 2nd last row and add in the new row in the Gridview
                    $('#gvStudent >tbody >tr').eq(intNoOfLines - 2).after('<tr style="background-color:white">' +
                        '<td><span id="Stid' + data.d.Stid + '">' + data.d.Stid + '</span></td>' +
                        '<td><span id="Name' + data.d.Stid + '">' + data.d.Name + '</span>' + '<input hidden type="text" id="txtName' + data.d.Stid + '" value="' + data.d.Name + '"></td>' +
                        '<td><span id="Gender' + data.d.Stid + '">' + data.d.Gender + '</span>' + '<select hidden id="selGender' + data.d.Stid + '"><option value="Male">Male</option><option value="Female" ' + (data.d.Gender === 'Female' ? 'selected' : '') + '>Female</option></select></td>' +
                        '<td><input type="checkbox" id="chkLocalStudent' + data.d.Stid + '" disabled ' + (data.d.LocalStudent === true ? 'checked' : '') + '></input></td>' +
                        '<td><table><tr><td><input type="button" id="btnEdit' + data.d.Stid + '" onclick="EditStudent(this.id);" value="Edit"/></td><td><input type="button" id="btnDelete' + data.d.Stid + '" onclick="DeleteStudent(this.id);" value="Delete"/></td></tr></table></td>' +
                        '</tr>');

                    //Empty the textbox and set the dropdownlist and radio buttons back to default values
                    $('#txtName').val('');
                    $('#selGender').val('Please Select');
                    $('input[name="rdLocalStudent"]').removeAttr('checked');
                    //The IF statement below will be executed if the jquery version is more than 1.x
                    //because ".removeAttr('checked')" for the radio button above doesn't work in jquery latest version.
                    if ($('input[name="rdLocalStudent"]:checked').val() !== undefined){
                        $('input[name="rdLocalStudent"]').prop('checked', false);
                    }
                },
                error: function (ex) {
                    alert(ex.responseText);
                }
            });
        });
    }

    function EditStudent(btnID) {

        $(document).ready(function () {

            //Get Student unique ID that hidden in Edit Button ID
            var stid = btnID.replace('btnEdit', '');

            //Hide the affected row data and show the textbox and dropdownlist and enable the checkbox. 
            if ($('#btnEdit' + stid).val() === 'Edit') {
                $('#btnEdit' + stid).val('Save');
                $('#btnDelete' + stid).attr('disabled', 'disabled');
                $('#Name' + stid).attr('hidden', 'hidden');
                $('#txtName' + stid).removeAttr('hidden');
                $('#Gender' + stid).attr('hidden', 'hidden');
                $('#selGender' + stid).removeAttr('hidden');
                $('#chkLocalStudent' + stid).removeAttr('disabled');
            }
            else {

                //Textbox (Name) can not be emmptied
                if ($('#txtName' + stid).val() === '') {
                    alert('Please enter the Name for Stid ' + stid + '.');
                    return;
                };
                //dropdownlist (Gender) can not be emptied
                if ($('#selGender' + stid + ' option:selected').val() === 'Please Select') {
                    alert('Please select the Gender for Stid ' + stid + '.');
                    return;
                };

                //Save new values
                $('#btnEdit' + stid).val('Edit');
                $('#btnDelete' + stid).removeAttr('disabled');
                $('#Name' + stid).removeAttr('hidden');
                $('#txtName' + stid).attr('hidden', 'hidden');
                $('#Gender' + stid).removeAttr('hidden');
                $('#selGender' + stid).attr('hidden', 'hidden');
                $('#chkLocalStudent' + stid).attr('disabled', 'disabled');

                //Get ready the new values to pass into Web Service
                var pName = $('#txtName' + stid).val();
                var pGender = $('#selGender' + stid).val();
                var pLocalStudent = $('#chkLocalStudent' + stid + ':checked') === true ? true : false;

                //Use Ajax to connect to the Web Service and save the new values into App_Data/Student.json file.
                $.ajax({
                    type: 'POST',
                    url: 'Default.aspx/EditStudent',
                    data: '{"pStid":' + stid + ', "pName":"' + pName + '", "pGender":"' + pGender + '", "pLocalStudent":' + pLocalStudent + '}',
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function () {
                        //Instead of getting 1 whole chunk of data from Web Service, 
                        //we can simply replace the affected row with new edited values
                        $('#Name' + stid).text(pName);
                        $('#Gender' + stid).text(pGender);
                        if (pLocalStudent === true) { $('#chkLocalStudent' + stid).attr('checked', 'checked') };
                    },
                    error: function (ex) {
                        alert(ex.responseText);
                    }
                });
            }
        });
    }

    function DeleteStudent(btnID) {

        $(document).ready(function () {

            //Get Student unique ID that hidden in Delete Button ID
            var stid = btnID.replace('btnDelete', '');

            //Use Ajax to connect to the Web Service and delete the data by Student unique ID from App_Data/Student.json file.
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/DeleteStudent',
                data: '{"pstid":' + stid + '}',
                contentType: 'application/json',
                dataType: 'json',
                success: function () {

                    //get the selected row index
                    var rowIndex = $('#Stid' + stid).closest('tr').index();
                    //Remove row by row index
                    $('#gvStudent >tbody >tr').eq(rowIndex).remove();
                },
                error: function (ex) {
                    alert(ex.responseText);
                }
            });
        });
    }

</script>
                                
                            

Step 10

Let's go to the code behind and add some codes in. Add these references at the top.

                                
using System.Data;
using System.Web.Services;
using Newtonsoft.Json;
using System.IO;
                                
                            

Step 11

Under Page_Load, we create a DataTable with columns and simply a row of data as a templete and let it bind into the Gridview. The pupose of this step is to create columns in the Gridview. That single row of data will be deleted at the client-side page.

                                
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Create datatable with columns
        DataTable dt = new DataTable();
        dt.Columns.Add("Stid", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Gender", typeof(string));
        dt.Columns.Add("LocalStudent", typeof(bool));
        dt.Columns.Add("Action", typeof(string));

        //Add an empty row into datatable
        DataRow rw = dt.NewRow();
        dt.Rows.Add(rw);

        //Bind the Gridview with datatble
        gvStudent.DataSource = dt;
        gvStudent.DataBind();
    }
}
                                
                            

Step 12

Add in a new class called 'Student' within the namespace. That means there will be 2 classes within this page (default class and Student class).

                                
public class Student
{
    public int Stid { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public bool LocalStudent { get; set; }
}
                                
                            

Step 13

Within the default class, create a function called 'RetrieveStudents' that helps us to read the Students.json file into a list of Students. And then create another function called 'RewriteStudentsJson' to helps to rewrite the students data into Students.json file when/if there are changes of the students data. These 2 functions must 'Static'.

                                
public static List<Student> RetrieveStudents()
{
    List<Student> lStudent = new List<Student>();

    //Read the Students.json file and transfer the students data into 'lStudent' object.
    using (StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath("~/App_Data/Students.json")))
    {
        string studentdata = sr.ReadToEnd();
        DataTable dtStudents = JsonConvert.DeserializeObject<DataTable>(studentdata);
        foreach (DataRow dr in dtStudents.Rows)
        {
            lStudent.Add(new Student()
            {
                Stid = Convert.ToInt32(dr["Stid"]),
                Name = dr["Name"].ToString(),
                Gender = dr["Gender"].ToString(),
                LocalStudent = Convert.ToBoolean(dr["LocalStudent"])
            });
        }
    }
    return lStudent;
}

public static void RewriteStudentsJson(List<Student> lStudent)
{
    //Rewrite all the students details into Students.json file. 
    string strStudents = JsonConvert.SerializeObject(lStudent, Formatting.Indented);
    File.WriteAllText(HttpContext.Current.Server.MapPath("~/App_Data/Students.json"), strStudents);
}
                                
                            

Step 14

Inside default class, create 4 '[WebMethod]' functions. These functions act as a Web Service and will be called from remote web clients.

                                
[WebMethod]
public static List<Student> GetStudent()
{
    //Retrieve a list of students from Students.json file
    List<Student> lStudent = RetrieveStudents();

    //Return the list of students to client-side (aspx file).
    return lStudent;
}

[WebMethod]
public static Student AddStudent(string pName, string pGender, bool pLocalStudent)
{
    //Retrieve a list of students from Students.json file
    List<Student> lStudent = RetrieveStudents();

    //Order the list of students by Stid and take the biggest number of Stid
    var q = lStudent.OrderByDescending(x => x.Stid).Select(x => new { x.Stid }).FirstOrDefault();

    //(Stid + 1) to create new Stid for new student
    Student stu = new Student() { Stid = q.Stid + 1, Name = pName, Gender = pGender, LocalStudent = pLocalStudent };

    //Add the new student with new Stid into the list of students
    lStudent.Add(stu);

    //Rewrite the whole list of students into the Students.json file.
    RewriteStudentsJson(lStudent);

    //Return the new student with new Stid back to client-side (aspx file).
    return stu;
}

[WebMethod]
public static void EditStudent(int pStid, string pName, string pGender, Boolean pLocalStudent)
{
    //Retrieve a list of students from Students.json file
    List<Student> lStudent = RetrieveStudents();

    //Select 1 of the student by Stid sent from client-side (aspx file)
    Student st = lStudent.Where(x => x.Stid == pStid).FirstOrDefault();

    //Change the student's detail with new values
    st.Name = pName;
    st.Gender = pGender;
    st.LocalStudent = pLocalStudent;

    //Rewrite the whole list of students into the Students.json file.
    RewriteStudentsJson(lStudent);
}

[WebMethod]
public static void DeleteStudent(int pstid)
{
    //Retrieve a list of students from Students.json file
    List<Student> lStudent = RetrieveStudents();

    //Remove the student by Stid from the list of students 
    lStudent.RemoveAll(x => x.Stid == pstid);

    //Rewrite the whole list of students into the Students.json file.
    RewriteStudentsJson(lStudent);
}
                                
                            

Now, run the solution and try out the Gridview with the functions of Add, Edit and Delete. Enjoy.

Author(s) Shoutout

Written by Amos Lai

Hi everyone, if you have any question, feel free to message me. If you like this article or would like me to extend more on the subject you can email me. Feedback is always appreciated. I will write more. If I get a two thumbs up. =)

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL).