CRUD operations in Kendo grid using angular js and webapi ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Thursday, 25 August 2016

CRUD operations in Kendo grid using angular js and webapi

05:49:00 Posted by raviteja swayampu , , 4 comments
This article will help you to implement CRUD operations on kendo grid using angular js.And i used webapi as data source for this application.In previous webapi  tutorials we saw the basic things like uploading files to web api,posting data to web api,Retriving and displaying web api data on html page.In this tutorial i am we will create kendo grid(a commercial API tool for web  designing). Previously i  implemented kendo grid using Jquery in this blog refer this link Kendo grid using Jquery.Now in present tutorial i am going to implement grid using Angular js.
This article flow as follows:
  1. Creating a ASP.NET Web api application,
  2. Creating a controller to display the grid(View),
  3. Include kendo reference files to View.
  4. Implement CRUD operations on grid. 

Creating a ASP.NET Web API application(Data Source)

1.Create a ASP.NET MVC application by picking a Empty MVC template.


CRUD operations in Kendo grid using angular js and webapi
2.Right click on App_Data folder and add Sql server to the project and create table schema as follows.
3.Data base code is as follows.
---Table Schema
CREATE TABLE [dbo].[TStudent] (
    [StudentID]   INT          IDENTITY (1, 1) NOT NULL,
    [FullName]    VARCHAR (50) NOT NULL,
    [Contact]     BIGINT       NOT NULL,
    [Country]     VARCHAR (50) NOT NULL,
    [Designation] VARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([StudentID] ASC)
);
---Insert some data into table
SET IDENTITY_INSERT [dbo].[TStudent] ON
INSERT INTO [dbo].[TStudent] ([StudentID], [FullName], [Contact], [Country], [Designation]) VALUES (1, N'Raviteja', 934348384, N'India', N'software trainee')
INSERT INTO [dbo].[TStudent] ([StudentID], [FullName], [Contact], [Country], [Designation]) VALUES (2, N'avinash', 903983473, N'china', N'trainee')
INSERT INTO [dbo].[TStudent] ([StudentID], [FullName], [Contact], [Country], [Designation]) VALUES (3, N'Rajk', 938483746, N'Canada', N'senior')
SET IDENTITY_INSERT [dbo].[TStudent] OFF

4.Add ADO.NET Entity Data Model to the project.
Note: In every sample project i am creating a ADO.DOT NET Entity Data Model.Because it automatically generates necessary files like Model objects,Connection string and Context Class required for project.

Add ADO.NET Entity Data Model

1.Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.

Create API Controller

1.Right click on Controllers --> Add --> Controller --> select web api Controller with method generated by Entity framework(Before this build solution once).
2.Select Model class and data context class.

CRUD operations in Kendo grid using angular js and webapi
3.Click add then visual studio automatically create scaffolding code with actions.
4.The generated code is as follows.


namespace AngularKendoGrid.Controllers
{
    public class TStudentsAPIController : ApiController
    {
        private StudentDBEntities db = new StudentDBEntities();

        // GET: api/TStudentsAPI
        public IQueryable GetTStudents()
        {
            return db.TStudents;
        }

        // GET: api/TStudentsAPI/5
        [ResponseType(typeof(TStudent))]
        [HttpGet]
        public async Task GetTStudent(int id)
        {
            TStudent tStudent = await db.TStudents.FindAsync(id);
            if (tStudent == null)
            {
                return NotFound();
            }

            return Ok(tStudent);
        }

        // PUT: api/TStudentsAPI/5
        [ResponseType(typeof(void))]
        [HttpPut]
        public async Task PutTStudent( TStudent tStudent)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            //if (id != tStudent.StudentID)
            //{
            //    return BadRequest();
            //}

            db.Entry(tStudent).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TStudentExists(tStudent.StudentID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/TStudentsAPI
        [ResponseType(typeof(TStudent))]
        [HttpPost]
        public async Task PostTStudent(TStudent tStudent)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.TStudents.Add(tStudent);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = tStudent.StudentID }, tStudent);
        }

        // DELETE: api/TStudentsAPI/5
        [ResponseType(typeof(TStudent))]
        [HttpDelete]
        public async Task DeleteTStudent(TStudent student)
        {
            TStudent tStudent = await db.TStudents.FindAsync(student.StudentID);
            if (tStudent == null)
            {
                return NotFound();
            }

            db.TStudents.Remove(tStudent);
            await db.SaveChangesAsync();

            return Ok(tStudent);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool TStudentExists(int id)
        {
            return db.TStudents.Count(e => e.StudentID == id) > 0;
        }
    }
}
5.Here i changed two methods parameters here
 public async Task DeleteTStudent(TStudent student)
{
}

 public async Task PutTStudent( TStudent tStudent)
{
}
6.Here for both methods there is a parameter int id.I removed it because kendo grid only sends the object data.
Note: compare the above code with the code generated by scaffolding and check.Then you will understand the changes easily by comparing.

Create a Controller and add Index action

1.Create another MVC controller and add View Index action to display the grid.
2.Add below  kendo reference files to Index view.


    <!--Kendo style reference files-->
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.flat.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.default.mobile.min.css" />
    
    <!--kendo script reference files-->
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/angular.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/jszip.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/kendo.all.min.js"></script>
3.The complete View code with Angular script is as follows.
    <!--Kendo style reference files-->
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.flat.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.default.mobile.min.css" />
    
    <!--kendo script reference files-->
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/angular.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/jszip.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/kendo.all.min.js"></script>

    <!--Kendo ui elements-->
    <!--Here k-options is kendo angular directive-->
    <div id="example" ng-app="KendoGridDemo">
        <h3>CRUD operations on Kendo grid using Angualr JS & webapi</h3>
        <div ng-controller="Controller">
            <kendo-grid k-options="mainGridOptions">
            </kendo-grid>
        </div>
    </div>

    <script>
        //Create a anular app and controller add kendo dependency to app
        angular.module("KendoGridDemo", ["kendo.directives"])
            .controller("Controller", function ($scope) {
                //specify kendo grid options
                $scope.mainGridOptions = {
                    dataSource: {
                        type: "json",   //data type
                        transport: {                          
                            destroy: {
                                url: "api/TStudentsAPI",
                                type: "DELETE"
                            }, read: {
                                url: "api/TStudentsAPI",    //http://localhost:13547/
                                dataType: "json",
                            },
                            create:
                            {
                                url: "api/TStudentsAPI",    //http://localhost:13547/
                                type: "POST"
                            },
                            update:
                            {
                                url: "api/TStudentsAPI",
                                type: "PUT",                               
                                parameterMap: function (options, operation) {
                                    if (operation !== "read" && options.models) {
                                        return {
                                            models: kendo.stringify(options.models)
                                        };
                                    }
                                }
                            },
                        },
                        schema: //schema of the table data
                                 {
                                     model:
                                     {
                                         id: "StudentID",
                                         fields: {
                                             StudentID: { editable: false, nullable: false, type: "number" },
                                             FullName: { editable: true, nullable: true, type: "string" },
                                             Contact: { editable: true, nullable: true, type: "number" },
                                             Country: { editable: true, nullable: true, type: "string" },
                                             Designation: { editable: true, nullable: true, type: "string" }
                                         }
                                     }
                                 },
                        pageSize: 5,
                        serverPaging: true,
                        serverSorting: true
                    },
                    editable: "popup",      //editable type popup/inline/batch
                    toolbar: ["create"],    //toolbar options
                    sortable: {
                        mode: "single",  //sorting
                        allowUnsort:true
                    },        
                    pageable: {          //paging
                        buttonCount: 5
                    },        
                    resizeable: true,       //resizing
                    scrollable: false,
                    //specify columns that you want to display 
                    columns: [{
                        field: "StudentID",
                        title: "Student ID",
                        width: "180px"
                    },
                    {
                        field: "FullName",
                        title: "FullName",
                        width: "180px"
                    },
                    {
                        field: "Contact",
                        title: "Contact",
                        width: "180px"
                    },
                    {
                        field: "Country",
                        title: "Country",
                        width: "180px"
                    },
                    {
                        field: "Designation",
                        title: "Designation",
                        width: "180px"
                    },
                    //actions columns contains-- edit/delete 
                        {
                            title:"Actions",
                            command: ["edit",
                            {
                                name: "destroy",
                                text: "Delete",
                                width: "120px"
                            }
                            ],
                        }
                    ]
                };
            });
    </script>
4.Now finally run the application and see the output..


CRUD operations in Kendo grid using angular js and webapi
Edit operation:
CRUD operations in Kendo grid using angular js and webapi
Delete:
CRUD operations in Kendo grid using angular js and webapi

Download the source code of this application here Source code(VS2015).

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

4 comments:

  1. Thanks a lots for giving like that article i am very happy to tell you i am find as long time like that example As CURD operation using Kendo UI thanks again.

    ReplyDelete
  2. Is there any .Net Version complexity, because when i was created a new project in VS2015 Community and started to implement this, I've failed to fetch data from the API, it shows an error "Resource could not be located". But when I've used your project as skeleton and put my customization over it, It works Nice. Any idea why this KOLAVERI D??
    TIA. :)

    ReplyDelete