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.
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using kendoCrudMvc.Models;
- using System.Globalization;
-
- namespace kendoCrudMvc.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult login()
- {
- return View();
- }
- [HttpPost]
- public ActionResult Index(UserModel users)
- {
- if (ModelState.IsValid==false)
- {
- return View(users);
- }
- Datalayer dl = new Datalayer();
- string sql = "";
- string strdate=users.dob.ToString();
- DateTime dt = DateTime.ParseExact(strdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
- users.dob = dt.ToString("yyyy-MM-dd").ToString();
- if (users.userid>0)
- {
- sql = "UPDATE public.tbluser SET \"email\"='"+users.email+"',\"mobile\"='"+users.mobile+"', \"password\" ='" + users.password + "', \"dob\" ='" + users.dob.ToString() + "' WHERE userid=" + users.userid + "";
- }
- else
- {
- sql = "Insert into tbluser(\"email\",\"mobile\",\"password\",\"dob\") values('" + users.email + "','" + users.mobile + "','" + users.password + "','" + users.dob + "')";
-
- }
-
-
- dl.query(sql);
- return RedirectToAction("Index");
- }
- [HttpPost]
- public JsonResult Getalluser()
- {
- Datalayer dl = new Datalayer();
- List<UserModel> userlist = dl.getusers();
- return Json(userlist);
- }
- [HttpPost]
- public ActionResult delete(int userid)
- {
- Datalayer dl = new Datalayer();
-
- string sql = "delete from tbluser where userid="+userid+"";
- dl.query(sql);
- return null;
- }
-
- }
- }
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.
- CREATE TABLE public.tbluser
- (
- userid integer NOT NULL DEFAULT nextval('tbluser_userid_seq'::regclass),
- email text COLLATE pg_catalog."default" NOT NULL,
- mobile text COLLATE pg_catalog."default" NOT NULL,
- password text COLLATE pg_catalog."default" NOT NULL,
- dob date NOT NULL,
- CONSTRAINT tbluser_pkey PRIMARY KEY (userid)
- )
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).
- using System.Web;
- using System.Web.Optimization;
-
- namespace kendoCrudMvc
- {
- public class BundleConfig
- {
-
- public static void RegisterBundles(BundleCollection bundles)
- {
- bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
- "~/Scripts/jquery-{version}.js"));
-
-
-
- bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
- "~/Scripts/bootstrap.js",
- "~/Scripts/respond.js"));
-
- bundles.Add(new StyleBundle("~/Content/css").Include(
- "~/Content/bootstrap.css",
- "~/Content/site.css"));
-
- bundles.Add(new StyleBundle("~/kendo/css").Include(
- "~/Content/kendo/kendo.common.min.css",
- "~/Content/kendo/kendo.common-bootstrap.min.css",
- "~/Content/kendo/kendo.bootstrap.min.css"
- ));
- bundles.Add(new ScriptBundle("~/kendo/js").Include(
- "~/Scripts/kendo/kendo.all.min.js"
- ));
- }
- }
- }
Step 7 -
Create UserModel from Models folder
Right-click on Models folder, click Add-> Class.
Paste the given code in UserModel.
- public class UserModel
- {
- public int userid { get; set; }
- [Required(ErrorMessage ="Email id Is required")]
- public string email { get; set; }
- [Required(ErrorMessage = "Mobile Number Is required")]
- public string mobile { get; set; }
- [Required(ErrorMessage = "Password Is required")]
- public string password { get; set; }
- [Required(ErrorMessage = "Confirm Password Is required")]
- [Compare("password", ErrorMessage = "Password and Confirmation Password must match.")]
- public string confirmpassword { get; set; }
- [Required(ErrorMessage = "Date Of Birth Is required")]
- public string dob { get; set; }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using Npgsql;
- using System.Configuration;
- using System.Data;
- using System.Globalization;
-
- namespace kendoCrudMvc.Models
- {
- public class Datalayer
- {
- NpgsqlConnection con = new NpgsqlConnection();
- public Datalayer()
- {
- con.ConnectionString = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
- }
- public void query(string sql)
- {
- NpgsqlCommand cmd = new NpgsqlCommand();
- cmd.CommandText = sql;
- cmd.CommandType = CommandType.Text;
- con.Open();
- cmd.Connection = con;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- con.Close();
- }
- public List<UserModel> getusers()
- {
- DataTable dt = new DataTable();
- DataSet ds = new DataSet();
- List<UserModel> userlist = new List<UserModel>();
- string sql = "select * from tbluser";
- NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, con);
- ds.Reset();
- da.Fill(ds);
- dt = ds.Tables[0];
- foreach (DataRow row in dt.Rows)
- {
- UserModel user = new UserModel();
- user.userid = Convert.ToInt32(row["userid"].ToString());
- user.email= row["email"].ToString();
- user.mobile = row["mobile"].ToString();
- user.password = row["password"].ToString();
- user.dob = row["dob"].ToString();
- string strdate = user.dob.ToString();
- DateTime date = DateTime.ParseExact(strdate, "dd-MM-yyyy HH:mm: ss", CultureInfo.InvariantCulture);
- user.dob = date.ToString("dd-MM-yyyy").ToString();
-
- userlist.Add(user);
- }
- return userlist;
- }
- }
- }
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.
- @using System.Web.Optimization
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>@ViewBag.Title</title>
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/kendo/js")
- @Scripts.Render("~/bundles/jqueryval")
- @Scripts.Render("~/bundles/modernizr")
- @Styles.Render("~/Content/css")
- @Styles.Render("~/kendo/css")
-
-
- </head>
- <body>
- <div>
- @RenderBody()
- </div>
- </body>
- </html>
-
- Step9: -Add below Code in View Folder - > Index.cshtml
- @model kendoCrudMvc.Models.UserModel
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_MasterPage.cshtml";
- }
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- @Html.HiddenFor(m => m.userid)
- <h2></h2>
- <div class="container">
- <div class="row">
- <div class="col-md-4">
- <div class="form-group">
- <label for="email">Email</label>
- @Html.TextBoxFor(m => m.email, null, new { @class = "form-control" })
- <span style="color:red;">@Html.ValidationMessageFor(m => m.email)</span>
-
- </div>
- <div class="form-group">
- <label for="mobile">Mobile</label>
- @Html.TextBoxFor(m => m.mobile, null, new { @class = "form-control" })
-
- <span style="color:red;"> @Html.ValidationMessageFor(m => m.mobile)</span>
- </div>
- <div class="form-group">
- <label for="password">Password</label>
- @Html.PasswordFor(m => m.password, new { @class = "form-control" })
- <span style="color:red;">@Html.ValidationMessageFor(m => m.password)</span>
-
- </div>
- <div class="form-group">
- <label for="confirmpassword">Confirm Password</label>
- @Html.PasswordFor(m => m.confirmpassword, new { @class = "form-control" })
- <span style="color:red;">@Html.ValidationMessageFor(m => m.confirmpassword)</span>
-
- </div>
- <div class="form-group">
- <label for="dob">Date Of Birth</label>
- @*<input id="dob" name="dob" />*@
- @Html.TextBoxFor(m=>m.dob)
- <br />
- <span style="color:red;">@Html.ValidationMessageFor(m => m.dob)</span>
-
- </div>
- <div class="form-group">
- <input type="submit" value="Submit" class="btn btn-primary" name="btninsert" />
- </div>
- </div>
- <div class="col-md-8">
- <div id="grid"></div>
- </div>
- </div>
- </div>
- <script type="text/javascript">
- $(document).ready(function () {
-
- $('body').on('click', '.edit', function () {
- debugger;
- $("#userid").val($(this).data("id"));
- $("#email").val($(this).data("email"));
- $("#mobile").val($(this).data("mobile"));
- $("#password").val($(this).data("password"));
- var d = $(this).data("date").slice(0, 10).split('-');
- var ddate = d[0] + '/' + d[1] + '/' + d[2];
- $("#dob").val(ddate);
- });
-
- });
- $("#dob").kendoDatePicker({
- format: "dd/MM/yyyy"
- });
-
- var datasource = new kendo.data.DataSource({
- transport: {
- read: {
- type: "POST",
- dataType: "json",
- url: "@Url.Action("Getalluser")",
- data: {}
- },
- destroy: {
- type: "POST",
- dataType: "json",
- url: "@Url.Action("delete")",
- data: {}
- }
- },
- schema: {
- model: {
- id: "userid",
- field: {
- email: { type: "string" },
- mobile: { type: "string" },
- password: { type: "string" },
- dob: { type: "date",format: "{0:dd-MM-yyyy}"}
- }
- }
- },
- pageSize: 4
- });
- $("#grid").kendoGrid({
- dataSource: datasource,
- columns: [
- {
- field: "email",
- title: "Email"
- },
- {
- field: "mobile",
- title: "Mobile"
- },
- {
- field: "password",
- title: "Password"
- },
- {
- field: "dob",
- title: "Date Of Birth",
- format: "{0:dd-MM-yyyy}"
- },
- {
- command: "destroy",
- title: "Delete"
- },
- {
- 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#' />",
- title: "Edit"
- }
- ],
- editable: "inline"
- }).data("kendoGrid");
- </script>
-
- }
-
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.