skip to main | skip to sidebar


Kendo UI Grid is a very popular widget for visualizing data tables. And in this example will demonstrate how to get CRUD(create/read/update/destroy) operations to work with ASP.Net(C#) Web Method.

Let's start by creating a Member class that will handle reading a list of members with server paging/sorting, plus updating/deleting one.
It does a very simple validation on Member email as an example of server-side validation.
For simplicity, will read members from a static list instead of querying a database.

public class Member
{
    /// <summary>
    /// Static list representing a Database table
    /// </summary>
    private static List<Member> MemberList = new List<Member>();

    public Guid? id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public bool active { get; set; }

    public static List<Member> GetList(List<Sort> sort, int skip, int take, out int total)
    {
        var list = MemberList.OrderBy(m => sort[0].field == "email" ? m.email : m.name).ToList();
        if (sort[0].dir == "desc") list.Reverse();

        total = list.Count;
        return list.Skip(skip).Take(take).ToList();
    }

    public static Member GetItem(Guid xID)
    {
        return MemberList.FirstOrDefault(x => x.id == xID);
    }

    /// <summary>
    /// return errors array or null for success
    /// </summary>
    public List<string> Validate()
    {
        var errors = new List<string>();
        if ((name ?? "").Trim() == "") errors.Add("Invalid Name");
        if ((email ?? "").Trim() == "" || !email.Contains("@")) errors.Add("Invalid Email");

        return errors.Count>0 ? errors : null;
    }

    /// <summary>
    /// return errors array or null for success
    /// </summary>
    public List<string> Save()
    {
        if (id == null)
        {
            id = Guid.NewGuid();
            MemberList.Add(this);
        }
        else
        {
            var i = MemberList.FindIndex(x => x.id == id);
            if (i <0) return new List<string> { "Item was not found" };
            MemberList[i] = this;
        }
        return null;
    }

    public void Delete()
    {
        MemberList.RemoveAll(x => x.id == id);
    }
}


Will also need these 2 classes for handling CRUD parameters
/// <summary>
/// Sorting field and direction
/// </summary>
public class Sort
{
    public string field { get; set; }
    public string dir { get; set; }
}


/// <summary>
/// CRUD Parameters
/// </summary>
public class Params
{
    public string type { get; set; }
    public List<Member> models { get; set; }
    public int skip { get; set; }
    public int take { get; set; }
    public List<Sort> sort { get; set; }
}


Now, let's have a look on the Web Method in Grid.aspx.cs that will handle all the CRUD operations.
    [WebMethod(enableSession: false)]
    public static object MemberCRUD(Params param)
    {
        if (param.type == "read")
        {
            if (param.sort == null || param.sort.Count ==0) param.sort = new List<Sort>{ new Sort{field = "name", dir = "asc"}};
            int total;
            var models = Member.GetList(param.sort, param.skip, param.take, out total);

            return new {models, total};
        }

        if (param.type == "destroy")
        {
            if (param.models == null || param.models.Count == 0) return new { errors = new[] { "Invalid data" } };

            param.models[0].Delete();
            return new { models = new List<Member> { param.models[0] } };
        }

        if (param.type == "create" || param.type == "update")
        {
       
            if (param.models == null || param.models.Count ==0) return new { errors = new [] { "Invalid data" } };

            var model = param.models[0];

            var errs = model.Validate();
            if(errs != null) return new { errors = errs };

            errs = model.Save();
            if (errs != null) return new { errors = errs };

            return new { models= new List<Member>{ model } };
        }

        return null;
    }


And finally, the HTML & jQuery code for initializing the Kendo UI Grid
<!DOCTYPE html>
<html>
<head>
    <title>Kendo UI Grid - MoreTechTips.net</title>
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2017.3.1026/styles/kendo.material.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2017.3.1026/styles/kendo.material.mobile.min.css" />

    <script src="//kendo.cdn.telerik.com/2017.3.1026/js/jquery.min.js"></script>
    <script src="//kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>
</head>
<body>
    <div id="grid"></div>

    <script>
        $(document).ready(function () {

            // setup datasource options
            var crudOp = {
                url: "Grid.aspx/MemberCRUD",
                type: "POST",
                contentType: "application/json; charset=utf-8", // send paramters as json
                dataType: "json"
            };

            var dataSource = new kendo.data.DataSource({
                transport: {
                    read: crudOp,
                    create: crudOp,
                    update: crudOp,
                    destroy: crudOp,
                    parameterMap: function (data, type) {
                        // send operation type
                        data.type = type;
                        // convert data to json string
                        return kendo.stringify({ param: data });
                    }
                },
                // initial sorting
                sort: {
                    field: 'name',
                    dir: 'asc'
                },
                requestEnd: function (e) {
                    if (e.type != "read" && e.response && !e.response.d.errors) {
                        // reload grid on create/update/delete and no errors
                        this.read();
                    }
                },
                error: function (e) {
                    if (!e.errors || !e.errors.length) return;

                    // prevent data-binding for one time and keep form opened
                    // cancel changes on the grid
                    var grid = $("#grid").data('kendoGrid');
                    grid.one("dataBinding", function (args) {
                        args.preventDefault();
                    });

                    alert(e.errors.join('\n'));
                },
                batch:true,
                pageSize: 10,
                serverPaging: true,
                serverSorting: true,
                schema: {
                    parse: function (response) {
                        // get rid of .d wrapper (from WebMethod response)
                        return response.d;
                    },
                    data: "models",
                    total: "total",
                    model: {
                        id: "id",
                        fields: {
                            id: { editable: false, nullable: true },
                            name: { validation: { required: true } },
                            email: { validation: { required: true } },
                            active: { type: "boolean" }
                        }
                    }
                }
            });

            // Initialize grid
            $("#grid").kendoGrid({
                dataSource: dataSource,
                pageable: true,
                sortable: {
                    allowUnsort: false
                },
                toolbar: ["create"],
                columns: [
                    "name",
                    "email",
                    { field: "active", sortable: false },
                    { command: ["edit", "destroy"], title: "" } ],
                editable: "popup"
            });
        });
    </script>

</body>
</html>

DataSource Configuration

Need to set type of AJAX query to "POST" and the contentType of the request to "application/json; charset=utf-8".

Using parameterMap function that will create request Params object to work with Asp.Net Web Method.

On requestEnd, need to reload the Grid to insert the newly created/updated record in the right page.

On error, we need to prevent the edit popup from closing, we must prevent the next dataBinding event.

Using parse function, to remove the "d" wrapper in JSON response from ASP.Net web method.

0 comments

Post a Comment

Thank you for taking the time to comment..
* If you have a tech issue with one of my plugins, you may email me on mike[at]moretechtips.net
More Tech Tips! | Technology tips on web development

Mike

Mike MoreWeb developer, jQuery plugin author, social media fan and Technology Blogger.
My favorite topics are: jQuery , Javascript , ASP.Net , Twitter , Google..
<connect with="me"> </connect>

Subscribe by email

Enter your email address:

or via RSS