In this demo, we have to learn how to use Kendo UI Grid with Web API Controller in ASP.Net Web Form.
In this demo, we have used database called "StudentDemo" and create a table called Students as shown below screen.
Note - You must add primary key row into table. If you did not add primary key than many functions like EDIT, UPDATE and DELETE can not work with Kendo UI Grid.
First Create Asp.Net Empty Web Form Project (Framework 4.0) and add Default.aspx page.
Now add below code to Default.aspx designer page.
Now, we have create Model Classes using Entity Framework.
Note - You must include the Entity Framework Reference using NuGet Package Manager.
Now add StudentModel.cs Class and add below code.
In the Next step, You have to add Web API Controller.
To add Web API Controller, First add Global.asax file and add below code to Global.asax file.
Now Right Click in the Project root and click Add => New Item => Select Web API Controller Class and Name this Controller to StudentController.cs as shown below screen.
Now add below code to StudentController.cs class.
Now add Connection string into web.config file.
Now Run the Project and you can able to create New Student and also you can edit, update and delete student from database.
Demo
Download Complete Source Code
In this demo, we have used database called "StudentDemo" and create a table called Students as shown below screen.
Note - You must add primary key row into table. If you did not add primary key than many functions like EDIT, UPDATE and DELETE can not work with Kendo UI Grid.
First Create Asp.Net Empty Web Form Project (Framework 4.0) and add Default.aspx page.
Now add below code to Default.aspx designer page.
<form id="form1" runat="server">
<div id="grid"></div>
<script type="text/javascript">
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/Student",
dataType: "json"
},
create: {
url: "/api/Student",
dataType: "json",
type: "POST"
},
update: {
url: "/api/Student",
dataType: "json",
type: "PUT"
},
destroy: {
url: "/api/Student",
dataType: "json",
type: "DELETE"
}
},
schema: {
model: {
id: "SId",
fields: {
SId: { editable: false, type: "number" },
SName: { validation: { required: true} },
SCity: { validation: { required: true} },
SRoleNo: { validation: { required: true }, type: "number" },
SDegree: { validation: { required: true} }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: [
"SId",
{ field: "SName", title: "Name" },
{ field: "SCity", title: "City" },
{ field: "SRoleNo", title: "Role" },
{ field: "SDegree", title: "Degree" },
{ command: ["edit"] },
{ command: ["destroy"] }
],
height: 330,
toolbar: [{ name: "create", text: "Create New Student"}],
editable: "popup"
});
});
</script>
</form>
Now, we have create Model Classes using Entity Framework.
Note - You must include the Entity Framework Reference using NuGet Package Manager.
Now add StudentModel.cs Class and add below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace KendoWebMethod
{
public class Student
{
[Key]
public int SId { get; set; }
public string SName { get; set; }
public string SCity { get; set; }
public int SRoleNo { get; set; }
public string SDegree { get; set; }
}
public class StdContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
}
In the Next step, You have to add Web API Controller.
To add Web API Controller, First add Global.asax file and add below code to Global.asax file.
using System.Web.Routing;
using System.Web.Http;
namespace KendoWebMethod
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
}
}
}
Now Right Click in the Project root and click Add => New Item => Select Web API Controller Class and Name this Controller to StudentController.cs as shown below screen.
Now add below code to StudentController.cs class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.Entity.Infrastructure;
namespace KendoWebMethod
{
public class StudentController : ApiController
{
StdContext kd = new StdContext();
// GET api/<controller>
[HttpGet]
public IEnumerable<Student> GetStudent()
{
return kd.Students.AsEnumerable();
}
// GET api/<controller>/5
[HttpGet]
public Student GetStudentById(int id)
{
Student students = kd.Students.Find(id);
if (students == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return students;
}
// POST api/<controller>
[HttpPost]
public HttpResponseMessage PostStudent(Student students)
{
if (ModelState.IsValid)
{
kd.Students.Add(students);
kd.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, students);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = students.SId }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
// PUT api/<controller>/5
[HttpPut]
public HttpResponseMessage PutStudent(int id, Student students)
{
if (ModelState.IsValid && id == students.SId)
{
kd.Entry(students).State = System.Data.EntityState.Modified;
try
{
kd.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, students);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
public HttpResponseMessage PutStudent(Student students)
{
return PutStudent(students.SId, students);
}
// DELETE api/<controller>/5
[HttpDelete]
public HttpResponseMessage DeleteStudent(int id)
{
Student students = kd.Students.Find(id);
if (students == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
kd.Students.Remove(students);
try
{
kd.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, students);
}
public HttpResponseMessage DeleteStudent(Student students)
{
return DeleteStudent(students.SId);
}
protected override void Dispose(bool disposing)
{
kd.Dispose();
base.Dispose(disposing);
}
}
}
Now add Connection string into web.config file.
<connectionStrings>
<add name="StdContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=StudentDemo;User ID=sa;Password=sa123" providerName="System.Data.SqlClient" />
</connectionStrings>
Now Run the Project and you can able to create New Student and also you can edit, update and delete student from database.
Demo
Download Complete Source Code
Great article, I am just getting into KendoUI and have a question
ReplyDeleteIf I have a table that I am populating from Powershell like this
protected void Page_Load(object sender, EventArgs e)
{
DoDataBind();
}
public void DoDataBind()
{
DataTable dt = CreateData();
RadGrid1.DataSource = dt.DefaultView;
RadGrid1.DataBind();
}
private DataTable CreateData()
{
UCSPowershellClass objManage1 = new UCSPowershellClass();
List items = objManage1.GetVLANs();
table = new DataTable();
table.Columns.Add("vlanID", typeof(string));
table.Columns.Add("vlanName", typeof(string));
table.Columns.Add("switchID", typeof(string));
foreach (string item in items)
{
string[] paramcolumns = item.Split('?');
table.Rows.Add(new object[] { paramcolumns[0].ToString(), paramcolumns[1].ToString(), paramcolumns[2].ToString() });
}
return table;
}
How would I bind that data to a Kendo GRID?
Any help or pointers would be appreciated
hi
ReplyDeletecan i change "edit" and "Delete" title in project
i try and i can change for example Starts with and ...
but i can not change edit and delete title in page