Friday 14 October 2016

What is JqGrid and implementing JqGrid in ASP.NET MVC

What is JqGrid and  implementing JqGrid in ASP.NET MVC
JqGrid  is an Ajax-enabled JavaScript control that provides solutions for representing and manipulating tabular data on the web. Since the grid is a client-side solution loading data dynamically through Ajax callbacks, it can be integrated with any server-side technology; PHP, ASP, JSP/Java Servlets, ColdFusion, Perl, etc.
-- Sql Query........................................

create database test
use test

create table Employee
(
EmpId int primary key,
Name varchar(50),
Gender varchar(50),
Salary int,
Doj date
)

First we  will take  Asp.Net Mvc Project  and right  click on solution Explore add JQuery.jqGrid  from NuGet  like  given below picture 



 after  we  will  work on Default Controller which name  HomeController




Code  for HomeController..........................................

 using System.Web.Mvc;
using JqGridConcept.Models;
using System;
using System.Linq;
using System.Data.Entity;

namespace JqGridConcept.Controllers
{

public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}

testEntities database = new testEntities();

// code  for get Employee Data  from table..................

public JsonResult GetEmployees(string sidx, string sort, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
{
sort = (sort == null) ? "" : sort;
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;

var empList = database.Employees.Select(emp => new
{
emp.EmpId,
emp.Name,
emp.Salary,
emp.Gender,
emp.Doj
});

if (_search)
{
switch (searchField)
{
case "EmpId":
empList = empList.Where(t => t.EmpId.ToString().Contains(searchString));
break;
case "Name":
empList = empList.Where(m => m.Name.Contains(searchString));
break;
case "Gender":
empList = empList.Where(m => m.Gender.Contains(searchString));
break;

case "Salary":
empList = empList.Where(m => m.Salary.ToString().Contains(searchString));
break;
case "Doj":
empList = empList.Where(m => m.Doj.ToString().Contains(searchString));
break;
}
}

int totalRecords = empList.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sort.ToUpper() == "DESC")
{
empList = empList.OrderByDescending(t => t.Name);
empList = empList.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
empList = empList.OrderBy(t => t.Name);
empList = empList.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = empList
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}



// code  for insert   data  in Employee table................

[HttpPost]
//public string Create([Bind(Exclude = "EmpId")] Employee Model)
public string Create(Employee Model)
{
string msg;
try
{
if (ModelState.IsValid)
{
// Model.EmpId = Guid.NewGuid().ToString();
database.Employees.Add(Model);
database.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfully";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}

// code  for update   data  in Employee table...............

public string Edit(Employee Model)
{
string msg;
try
{
if (ModelState.IsValid)
{
database.Entry(Model).State = EntityState.Modified;
database.SaveChanges();
msg = "Update  Successfully";
}
else
{
msg = "Validation data not successfully";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}

// code  for delete   data  in Employee table

public string Delete(string Id)
{
int empId = Convert.ToInt32(Id);
var result = database.Employees.Where(m => m.EmpId == empId).FirstOrDefault();
if (result != null)
{
database.Employees.Remove(result);
database.SaveChanges();
return "Deleted successfully";
}
else
{
return "Some Error";
}
}
}
}


Code  for Index.cshtml..........................................


@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>

<link href="~/Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-2.2.3.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/jquery-ui-1.10.0.js"></script>
@*<script src="~/Scripts/jquery-ui-1.10.4.js"></script>*@


<script src="~/Scripts/jquery.jqGrid.min.js"></script>



<script type="text/javascript">

$(function ()
{
$("#jqGrid").jqGrid(
{
url: "/Home/GetEmployees",
datatype: 'json',
mtype: 'Get',
colNames: ['EmpId', 'Name','Gender', 'Salary', 'Joining Date'],

colModel: [
//{ key: true, hidden: true, name: 'EmpId', index: 'EmpId', editable: true },
{ key: true,  name: 'EmpId', index: 'EmpId', editable: true },
{ key: false, name: 'Name', index: 'Name', editable: true },
{ key: false, name: 'Gender', index: 'Gender', editable: true, edittype: 'select', editoptions: { value: { 'M': 'Male', 'F': 'Female', 'N': 'None' } } },
{ key: false, name: 'Salary', index: 'Salary', editable: true },
{ key: false, name: 'Doj', index: 'Doj', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' } }],

pager: jQuery('#jqControls'),
rowNum: 10,
rowList: [10, 20, 30, 40, 50],
height: '100%',
viewrecords: true,
caption: 'Employee Records',
emptyrecords: 'No Employee Records are Available to Display',
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
autowidth: true,
multiselect: false
}).navGrid('#jqControls', {
edit: true, add: true, del: true, search: true,
searchtext: "Search Employee", refresh: true
},
{
zIndex: 100,
url: '/Home/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
zIndex: 100,
url: "/Home/Create",
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
zIndex: 100,
url: "/Home/Delete",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete Employee... ? ",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
zIndex: 100,
caption: "Search Employee",
sopt: ['cn']
});
});

</script>
</head>

<body>
<h2>Employee Information</h2>
<div>
<table id="jqGrid"></table>
<div id="jqControls"></div>
</div>
</body>
</html>

Result


0 comments:

Post a Comment