this is for index.cshtml page:-
@using TestDemo16_nov.Models;
@model List<UserViewModel>
@{
ViewBag.Title = "Home Page";
}
@*<link href="~/Content/Jq%20grid/jquery-ui-custom.css" rel="stylesheet" />*@
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/Jqgrid/jquery-ui-1.8.7.css" rel="stylesheet" />
<link href="~/Content/Jqgrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/Jqgrid/grid.locale-en.js"></script>
<script src="~/Scripts/Jqgrid/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<style type="text/css">
.userRow {
color: #0769AD !important;
}
</style>
<script type="text/javascript">
/****************this is to edit the user**********************/
function EditUser(id) {
$.ajax({
url: "@Url.Action("EditUser", "Home")" + "?id=" + id,
data: "userId=" + id,
success: function (result) {
$("#divEditUser").html(result);
$("#divEditUser").dialog("open");
}
});
}
/*******************this is used to start the overlay(loader)***********************/
function loaderStart() {
$('#loader').show();
}
/*******************this is used to stop the overlay(loader)***********************/
function loaderStop() {
setTimeout('$("#loader").hide()', 100);
}
/****************this is to delete the user**********************/
function DeleteUser(id) {
var r = confirm("Do you want to delete this User?");
if (r == true) {
$.ajax({
type: "POST",
url: "/Home/DeleteUser",
async: false,
data: "userId=" + id,
success: function (data) {
if (data == 'True') {
RefreshGrid();
alert('User deleted successfully.');
}
else {
alert('Some error is occured while deleting.');
}
}
});
}
}
/********************To refresh grid****************/
function RefreshGrid() {
$("#list").jqGrid().setGridParam({
url: '/Home/LinqGridData/',
datatype: 'json'
}).trigger("reloadGrid");
}
$(function () {
/******************this is used to add new user*******************/
$("#AddUser").click(function () {
$.ajax({
url: "@Url.Action("EditUser", "Home")" + "?id=" + 0,
success: function (result) {
$("#divEditUser").html(result);
$("#divEditUser").dialog("open");
}
});
});
/******************this is used to open dialog for user Add/Edit*******************/
$("#divEditUser").dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
/******************this is used to show user*******************/
$("#list").jqGrid({
url: '/Home/LinqGridData/',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'Name', 'Email', 'Action'],
colModel: [
{ name: 'Id', index: 'Id', width: 120, align: 'center', hidden: true },
{ name: 'Name', index: 'Id', width: 170, align: 'center' },
{ name: "Email", index: 'Email', width: 170, align: 'center' },
{ name: 'act', width: 138, sortable: false }
],
pager: $('#pager'),
rowNum: 5,
rowList: [5, 10, 15, 20, 50],
sortname: 'Id',
sortorder: 'desc',
sortable: true,
height: "100%",
viewrecords: true,
imgpath: '',
caption: 'User List',
gridComplete: function () {
var ids = $("#list").jqGrid('getDataIDs');
var myCellData;
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
var grid = $('#list');
myCellData = grid.jqGrid('getCell', cl, 'Id');
ed = "<input style='height:30px;width:50px;' type='button' value='Edit' onclick=\"EditUser(" + myCellData + ");\" />";
de = "<input style='height:30px;width:70px;' type='button' value='Delete' onclick=\"DeleteUser(" + myCellData + ");\" />";
$("#list").jqGrid('setRowData', ids[i], { act: ed + "|" + de });
}
}
});
});
</script>
<form id="frmUser">
<a href="#" id="AddUser">Add User</a>
<fieldset>
<legend class="fieldset">User List</legend>
<table id="list" class="scroll" cellpadding="0" cellspacing="0">
</table>
<div id="pager" class="scroll" style="text-align: center;">
</div>
</fieldset>
</form>
<div id="divEditUser" title="Basic dialog">
</div>
<div class="loader" id="loader" style="display: none">
<span class="ui-icon"> </span>
</div>
:-----------------------
in the above code you find everything that you required...
controller code is given bellow:-
using System.Web;
using System.Web.Mvc;
using TestDemo16_nov.Models;
namespace TestDemo16_nov.Controllers
{
/// <summary>
/// this is used for user
/// </summary>
public class HomeController : Controller
{
private testDBEntities dbEntities = new testDBEntities();
/// <summary>
/// this is used to show the all user information list.
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
var lstUser = (from user in dbEntities.tblusers
select new UserViewModel
{
Id = user.id,
Name = user.Name,
Email = user.Email
}).OrderByDescending(c=>c.Id).ToList();
return View(lstUser);
}
/// <summary>
/// To delete user data
/// </summary>
/// <returns></returns>
[AcceptVerbs(HttpVerbs.Post)]
public bool DeleteUser(string userId)
{
try
{
int id = Convert.ToInt32(userId);
var objUser = dbEntities.tblusers.Where(c => c.id == id).FirstOrDefault();
dbEntities.tblusers.Remove(objUser);
dbEntities.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// To edit user data
/// </summary>
/// <returns></returns>
public ActionResult EditUser(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new FieldAccessException();
}
if (id.Equals("0"))
{
var user = new UserViewModel();
return PartialView(user);
}
else {
int userId = Convert.ToInt32(id);
var objUser = dbEntities.tblusers.Where(c => c.id == userId).FirstOrDefault();
var user = new UserViewModel
{
Id = objUser.id,
Name = objUser.Name,
Email = objUser.Email
};
return PartialView(user);
}
}
[HttpPost]
/// <summary>
/// To edit user data
/// </summary>
/// <returns></returns>
public ActionResult EditUser(UserViewModel model)
{
if (model.Id == 0)
{
var newUser = new tbluser
{
Email=model.Email,
Name=model.Name
};
dbEntities.tblusers.Add(newUser);
dbEntities.SaveChanges();
return RedirectToAction("Index");
}
var objUser = dbEntities.tblusers.Where(c => c.id == model.Id).FirstOrDefault();
objUser.Email = model.Email;
objUser.Name = model.Name;
dbEntities.SaveChanges();
return RedirectToAction("Index");
}
/// <summary>
/// Function to bind Grid Data
/// </summary>
/// <param name="sidx"></param>
/// <param name="sord"></param>
/// <param name="page"></param>
/// <param name="rows"></param>
/// <returns></returns>
public ActionResult LinqGridData(string sidx, string sord, int page, int rows)
{
int pageSize = rows;
int pageIndex = Convert.ToInt32(page) - 1;
var lstUser = (from user in dbEntities.tblusers
select new UserViewModel
{
Id = user.id,
Name = user.Name,
Email = user.Email
}).OrderByDescending(c=>c.Id).ToList();
int totalRecords = lstUser.Count;
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
lstUser = lstUser.Skip(pageIndex * pageSize)
.Take(pageSize).ToList();
var jsonData = new
{
total = totalPages, //todo: calculate
page,
records = totalRecords,
rows = (
from usr in lstUser
select new
{
i = usr.Id,
cell = new string[] { usr.Id.ToString(), usr.Name, usr.Email }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
}
-------
you need to create the edmx and bind. one partial view is require so you need to create in Shared folder with name "EditUser" the html code is given bellow :
@model TestDemo16_nov.Models.UserViewModel
<h2>EditUser</h2>
@using (Html.BeginForm())
{
<fieldset>
<legend>Edit User</legend>
<ol>
<li>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
</li>
<li>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email)
</li>
</ol>
<input type="submit" id="btnSubmit" value="Save" />
</fieldset>
}
----
here I am using UserViewModel model so please create it like given bellow:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestDemo16_nov.Models
{
/// <summary>
/// this is used fatch/insert the user information from the database table tbluser.
/// </summary>
public class UserViewModel
{
/// <summary>
/// this is unique key for user.
/// </summary>
public int Id { get; set; }
/// <summary>
/// this is for email of user.
/// </summary>
public string Email { get; set; }
/// <summary>
/// this is used to name of user.
/// </summary>
public string Name { get; set; }
}
}
-----------------