CRUD Operation In MVC Using Kendo UI

In this article, you will learn how to fully enable the Create, Read, Update, Destroy (CRUD) data operations in the Grid in ASEP.NET MVC using Kendo UI.
 
Create a new MVC project.
 
Step 1

Open Visual Studio.
 
 

Select a new project from the File menu.

 

Select ASP.NET Web Application and click OK.

 
 
Select MVC and click OK.
 
 
  
Step 2- Adding new HomeController

Right-click on Controllers folder >> Add >> Controller.
 
 
 
User needs to select the MVC 5 Controller-Empty in "Add Scaffold" dialog and click "Add".
 
 
 
 Give Controller a name as Home.Controller and click "Add".
 
 
 
Paste the below code in Home.Controller.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using kendoCrudMvc.Models;  
  7. using System.Globalization;  
  8.   
  9. namespace kendoCrudMvc.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         // GET: Home  
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.         public ActionResult login()  
  19.         {  
  20.             return View();  
  21.         }  
  22.         [HttpPost]  
  23.         public ActionResult Index(UserModel users)  
  24.         {  
  25.             if (ModelState.IsValid==false)  
  26.             {  
  27.                 return View(users);  
  28.             }  
  29.             Datalayer dl = new Datalayer();  
  30.             string sql = "";  
  31.             string strdate=users.dob.ToString();  
  32.             DateTime dt = DateTime.ParseExact(strdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);  
  33.             users.dob = dt.ToString("yyyy-MM-dd").ToString();  
  34.             if (users.userid>0)  
  35.             {  
  36.                 sql = "UPDATE public.tbluser SET \"email\"='"+users.email+"',\"mobile\"='"+users.mobile+"', \"password\" ='" + users.password + "', \"dob\" ='" + users.dob.ToString() + "' WHERE userid=" + users.userid + "";   
  37.             }  
  38.             else  
  39.             {  
  40.                  sql = "Insert into tbluser(\"email\",\"mobile\",\"password\",\"dob\") values('" + users.email + "','" + users.mobile + "','" + users.password + "','" + users.dob + "')";  
  41.   
  42.             }  
  43.   
  44.   
  45.             dl.query(sql);  
  46.             return RedirectToAction("Index");  
  47.         }  
  48.         [HttpPost]  
  49.         public JsonResult Getalluser()  
  50.         {  
  51.             Datalayer dl = new Datalayer();  
  52.             List<UserModel> userlist = dl.getusers();  
  53.             return Json(userlist);  
  54.         }  
  55.         [HttpPost]  
  56.         public ActionResult delete(int userid)  
  57.         {  
  58.             Datalayer dl = new Datalayer();  
  59.               
  60.             string sql = "delete from tbluser where userid="+userid+"";  
  61.             dl.query(sql);  
  62.             return null;  
  63.         }  
  64.   
  65.     }  
  66. }  
Step 3

Download the kendo CSS and JS files from below. Click on "Download a free trial" link.

https://www.telerik.com/download/kendo-ui-core
 
 

Once the user completes the download, it shows the below folder.
 
 
 
Click "Style" folder, all the CSS files will be displayed which need to be included in the Content folder.
 
  
 
In JS folder, all the JS files will be displayed which need to be included in Script folder.
 
 

Following are the step to include CSS file in project's Content folder

Create one folder named Kendo inside Content folder and paste CSS files.
 
 
 
Include JavaScript files in Scripts folder.
 
 
 
Step 4 - Create table in Database Pgadmin (PostgreSQL)

Below is the query to create a table in Database.
  1. CREATE TABLE public.tbluser  
  2. (  
  3.    userid integer NOT NULL DEFAULT nextval('tbluser_userid_seq'::regclass),  
  4.    email text COLLATE pg_catalog."default" NOT NULL,  
  5.    mobile text COLLATE pg_catalog."default" NOT NULL,  
  6.    password text COLLATE pg_catalog."default" NOT NULL,  
  7.    dob date NOT NULL,  
  8.    CONSTRAINT tbluser_pkey PRIMARY KEY (userid)  
  9. )   
Output of the table with data -
 
 
 
Step 5

Insert the Connection string in web.config file in ASP.NET.
 
 
 
Step 6

Select App_Start folder and open Bundleconfig.cs file and include the following CSS and JS (Code is given below).
 
 
  1. using System.Web;  
  2. using System.Web.Optimization;  
  3.   
  4. namespace kendoCrudMvc  
  5. {  
  6.     public class BundleConfig  
  7.     {  
  8.         // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862  
  9.         public static void RegisterBundles(BundleCollection bundles)  
  10.         {  
  11.             bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  12.                         "~/Scripts/jquery-{version}.js"));  
  13.   
  14.   
  15.   
  16.             bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(  
  17.                       "~/Scripts/bootstrap.js",  
  18.                       "~/Scripts/respond.js"));  
  19.   
  20.             bundles.Add(new StyleBundle("~/Content/css").Include(  
  21.                       "~/Content/bootstrap.css",  
  22.                       "~/Content/site.css"));  
  23.   
  24.             bundles.Add(new StyleBundle("~/kendo/css").Include(  
  25.                 "~/Content/kendo/kendo.common.min.css",  
  26.                 "~/Content/kendo/kendo.common-bootstrap.min.css",  
  27.                 "~/Content/kendo/kendo.bootstrap.min.css"  
  28.                 ));  
  29.             bundles.Add(new ScriptBundle("~/kendo/js").Include(  
  30.                     "~/Scripts/kendo/kendo.all.min.js"  
  31.                 ));  
  32.         }  
  33.     }  
  34. }  
Step 7 - Create UserModel from Models folder
 
Right-click on Models folder, click Add-> Class.
 
 
 
Paste the given code in UserModel.
  1. public class UserModel  
  2.     {  
  3.         public int userid { getset; }  
  4.         [Required(ErrorMessage ="Email id Is required")]  
  5.         public string email { getset; }  
  6.         [Required(ErrorMessage = "Mobile Number Is required")]  
  7.         public string mobile { getset; }  
  8.         [Required(ErrorMessage = "Password Is required")]  
  9.         public string password { getset; }  
  10.         [Required(ErrorMessage = "Confirm Password Is required")]  
  11.         [Compare("password", ErrorMessage = "Password and Confirmation Password must match.")]  
  12.         public string confirmpassword { getset; }  
  13.         [Required(ErrorMessage = "Date Of Birth Is required")]  
  14.         public string dob { getset; }  
  15.     }  
Data layer class in model folder

Right-click Models folder and add a new class and give it a name DataLayer.cs. It is used as a help file to database connection and query execution.
 
 
 
Write the following code in DataLayer.cs file.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using Npgsql;  
  6. using System.Configuration;  
  7. using System.Data;  
  8. using System.Globalization;  
  9.   
  10. namespace kendoCrudMvc.Models  
  11. {  
  12.     public class Datalayer  
  13.     {  
  14.         NpgsqlConnection con = new NpgsqlConnection();  
  15.         public Datalayer()  
  16.         {  
  17.             con.ConnectionString = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;  
  18.         }  
  19.         public void query(string sql)  
  20.         {  
  21.             NpgsqlCommand cmd = new NpgsqlCommand();  
  22.             cmd.CommandText = sql;  
  23.             cmd.CommandType = CommandType.Text;  
  24.             con.Open();  
  25.             cmd.Connection = con;  
  26.             cmd.ExecuteNonQuery();  
  27.             cmd.Dispose();  
  28.             con.Close();  
  29.         }  
  30.         public List<UserModel> getusers()  
  31.         {  
  32.             DataTable dt = new DataTable();  
  33.             DataSet ds = new DataSet();  
  34.             List<UserModel> userlist = new List<UserModel>();  
  35.             string sql = "select * from tbluser";  
  36.             NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, con);  
  37.             ds.Reset();  
  38.             da.Fill(ds);  
  39.             dt = ds.Tables[0];  
  40.             foreach (DataRow row in dt.Rows)  
  41.             {  
  42.                 UserModel user = new UserModel();  
  43.                 user.userid = Convert.ToInt32(row["userid"].ToString());  
  44.                 user.email= row["email"].ToString();  
  45.                 user.mobile = row["mobile"].ToString();  
  46.                 user.password = row["password"].ToString();  
  47.                 user.dob = row["dob"].ToString();  
  48.                 string strdate = user.dob.ToString();  
  49.                 DateTime date = DateTime.ParseExact(strdate, "dd-MM-yyyy HH:mm: ss", CultureInfo.InvariantCulture);  
  50.                 user.dob = date.ToString("dd-MM-yyyy").ToString();  
  51.   
  52.                 userlist.Add(user);  
  53.             }  
  54.             return userlist;  
  55.         }  
  56.     }  
  57. }  
Step 8

Create a new Layout Page, give a name as “_MasterPage.chtml” and write the following code.

Right-click on View/Shared -> click Add -> select New item.
 
 
 
Select MVC 5 layout page (Razor) and click on "Add" button.
 
 
 
Add the following code in layout page.
  1. @using System.Web.Optimization  
  2. <!DOCTYPE html>  
  3. <html>  
  4. <head>  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <title>@ViewBag.Title</title>  
  7.     @Scripts.Render("~/bundles/jquery")  
  8.     @Scripts.Render("~/kendo/js")  
  9.     @Scripts.Render("~/bundles/jqueryval")  
  10.     @Scripts.Render("~/bundles/modernizr")  
  11.     @Styles.Render("~/Content/css")  
  12.     @Styles.Render("~/kendo/css")  
  13.   
  14.       
  15. </head>  
  16. <body>  
  17.     <div>  
  18.         @RenderBody()  
  19.     </div>  
  20. </body>  
  21. </html>  
  22.   
  23. Step9: -Add below Code in View Folder - > Index.cshtml  
  24. @model kendoCrudMvc.Models.UserModel  
  25. @{  
  26.     ViewBag.Title = "Index";  
  27.     Layout = "~/Views/Shared/_MasterPage.cshtml";  
  28. }  
  29.   
  30. @using (Html.BeginForm())  
  31. {  
  32.     @Html.AntiForgeryToken()  
  33.     @Html.HiddenFor(m => m.userid)  
  34.     <h2></h2>  
  35.     <div class="container">  
  36.         <div class="row">  
  37.             <div class="col-md-4">  
  38.                 <div class="form-group">  
  39.                     <label for="email">Email</label>  
  40.                     @Html.TextBoxFor(m => m.email, nullnew { @class = "form-control" })  
  41.                     <span style="color:red;">@Html.ValidationMessageFor(m => m.email)</span>  
  42.   
  43.                 </div>  
  44.                 <div class="form-group">  
  45.                     <label for="mobile">Mobile</label>  
  46.                     @Html.TextBoxFor(m => m.mobile, nullnew { @class = "form-control" })  
  47.   
  48.                     <span style="color:red;">  @Html.ValidationMessageFor(m => m.mobile)</span>  
  49.                 </div>  
  50.                 <div class="form-group">  
  51.                     <label for="password">Password</label>  
  52.                     @Html.PasswordFor(m => m.password, new { @class = "form-control" })  
  53.                     <span style="color:red;">@Html.ValidationMessageFor(m => m.password)</span>  
  54.                      
  55.                 </div>  
  56.                 <div class="form-group">  
  57.                     <label for="confirmpassword">Confirm Password</label>  
  58.                     @Html.PasswordFor(m => m.confirmpassword, new { @class = "form-control" })  
  59.                     <span style="color:red;">@Html.ValidationMessageFor(m => m.confirmpassword)</span>  
  60.                      
  61.                 </div>  
  62.                 <div class="form-group">  
  63.                     <label for="dob">Date Of Birth</label>  
  64.                     @*<input id="dob" name="dob" />*@  
  65.                     @Html.TextBoxFor(m=>m.dob)  
  66.                     <br />  
  67.                     <span style="color:red;">@Html.ValidationMessageFor(m => m.dob)</span>  
  68.                       
  69.                 </div>  
  70.                 <div class="form-group">  
  71.                     <input type="submit" value="Submit" class="btn btn-primary" name="btninsert" />  
  72.                 </div>  
  73.             </div>  
  74.             <div class="col-md-8">  
  75.                 <div id="grid"></div>  
  76.             </div>  
  77.         </div>  
  78.     </div>  
  79.     <script type="text/javascript">  
  80.         $(document).ready(function () {  
  81.   
  82.             $('body').on('click''.edit', function () {  
  83.                 debugger;  
  84.                 $("#userid").val($(this).data("id"));  
  85.                 $("#email").val($(this).data("email"));  
  86.                 $("#mobile").val($(this).data("mobile"));  
  87.                 $("#password").val($(this).data("password"));  
  88.                 var d = $(this).data("date").slice(0, 10).split('-');  
  89.                 var ddate = d[0] + '/' + d[1] + '/' + d[2];  
  90.                 $("#dob").val(ddate);  
  91.             });  
  92.   
  93.         });  
  94.         $("#dob").kendoDatePicker({  
  95.             format: "dd/MM/yyyy"  
  96.         });  
  97.   
  98.         var datasource = new kendo.data.DataSource({  
  99.             transport: {  
  100.                 read: {  
  101.                     type: "POST",  
  102.                     dataType: "json",  
  103.                     url: "@Url.Action("Getalluser")",  
  104.                     data: {}  
  105.                 },  
  106.                 destroy: {  
  107.                     type: "POST",  
  108.                     dataType: "json",  
  109.                     url: "@Url.Action("delete")",  
  110.                     data: {}  
  111.                 }  
  112.             },  
  113.             schema: {  
  114.                 model: {  
  115.                     id: "userid",  
  116.                     field: {  
  117.                         email: { type: "string" },  
  118.                         mobile: { type: "string" },  
  119.                         password: { type: "string" },  
  120.                         dob: { type: "date",format: "{0:dd-MM-yyyy}"}  
  121.                     }  
  122.                 }  
  123.             },  
  124.             pageSize: 4  
  125.         });  
  126.         $("#grid").kendoGrid({  
  127.             dataSource: datasource,  
  128.             columns: [  
  129.                 {  
  130.                     field: "email",  
  131.                     title: "Email"  
  132.                 },  
  133.                  {  
  134.                      field: "mobile",  
  135.                      title: "Mobile"  
  136.                  },  
  137.                  {  
  138.                      field: "password",  
  139.                      title: "Password"  
  140.                  },  
  141.                  {  
  142.                      field: "dob",  
  143.                      title: "Date Of Birth",  
  144.                      format: "{0:dd-MM-yyyy}"  
  145.                  },  
  146.                  {  
  147.                      command: "destroy",  
  148.                      title: "Delete"  
  149.                  },  
  150.                  {  
  151.                      template: "<input type='button' value='edit' class='k-button edit' data-id='#=userid#' data-email='#=email#' data-mobile='#=mobile#' data-password='#=password#' data-date='#=dob#' />",  
  152.                      title: "Edit"  
  153.                  }  
  154.             ],  
  155.             editable: "inline"  
  156.         }).data("kendoGrid");  
  157.     </script>  
  158.   
  159. }  
  160.   
Press F5 to Build and Run the project.
 
 
 
I hope you liked the article. If you have any query, please feel free to post in the comments section.


Similar Articles