jqgrid implementation using JSOn and asp.net - asp.net

Last time, I asked similar question. Now I tried to put the jqgrid together to work. However, I tried to bring the grid but the data is not loading.
here are the two files
GetData.aspx
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Script.Serialization"%>
<%# Import Namespace="System.Collections.ObjectModel"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(GetData());
Response.End();
//Response.Write ("Data is being loaded");
}
protected string GetData()
{
var list = new Collection<People>
{
new People {Id = 1, Name = "John", Gender = 1, IsClosed = false},
new People {Id = 2, Name = "Abel", Gender = 1, IsClosed = false},
new People {Id = 3, Name = "Aaron", Gender = 1, IsClosed = true},
new People {Id = 4, Name = "Tsion", Gender = 2, IsClosed = true},
new People {Id = 5, Name = "Mussie", Gender = 2, IsClosed = true}
};
return GridData(1, 1, list.Count, list);
}
public string GridData(int noOfPages, int startPage, int noOfRecords, Collection<People> list)
{
var gridData = new
{
total = noOfPages,
page = startPage,
records = noOfRecords,
rows = list,
};
var jsonSerializer = new JavaScriptSerializer();
return jsonSerializer.Serialize(gridData);
}
public class People
{
public People()
{
Name = string.Empty;
Id = 0;
Gender = 0;
IsClosed = false;
}
public string Name { get; set; }
public int Id { get; set; }
public int Gender { get; set; }
public bool IsClosed { get; set; }
}
public enum Oper
{
edit=1,
del=2,
add=3
}
</script>
</html>
JQExample.aspx
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head id="Head1" runat="server">
<title>JqGrid</title>
<link href="themes/redmond/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />
<link href="themes/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.jqGrid.js" type="text/javascript"></script>
</head>
<body>
<%-- <form id="form1">--%>
<table id="jsonmap">
</table>
<div id="pjmap">
</div>
<script type="text/javascript">
jQuery("#jsonmap").jqGrid({
url: 'GetData.aspx',
datatype: 'json',
colNames: ['ID', 'Name','Active','Gender'],
colModel: [{
name: 'id',
index: 'id',
width: 35,
editable: false,
editoptions: {
readonly: true,
size: 10
}},
{
name: 'name',
index: 'name',
width: 150,
align: "left",
editable: true,
size: 100
},
{
name: 'isClosed',
index: 'isClosed',
width: 100,
align: 'left',
editable: true,
edittype: "checkbox",
editoptions: {
value: "true:false",
formatter: "checkbox"
}},
{
name: 'gender',
index: 'gender',
width: 100,
formatter:'select',
editable: true,
edittype: "select",
editoptions: {value: "0:select;1:male;2:female"}
}],
rowNum: 10,
rowList: [2, 5, 10, 15],
pager: '#pjmap',
sortname: 'id',
sortorder: "desc",
viewrecords: true,
jsonReader: {
repeatitems: false
},
width: 600,
caption: 'First jqGrid',
height: '100%',
editurl: 'GetData.aspx'
});
jQuery("#jsonmap").navGrid("#pjmap", {
edit: true,
add: true,
del: true
},
{
closeAfterEdit: true,
reloadAfterSubmit: false
},
{
closeAfterAdd: true,
reloadAfterSubmit: false
},
{
reloadAfterSubmit: false
});
</script>
<table id="Jqgrid" width="100%">
</table>
<div id="pager"></div>
</form>
</body>
</html>
Now I would like to change data to be displayed dynamically using ADO.net.
Thank you sir. It worked now.
I want to change to get data dynamically which is change the data source in GetData.aspx and format the colNames and ColModel in JQExample.aspx file:
$(document).ready(function () {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
//url: "GetData.aspx",
datatype: 'json',
success: function (result) {
// colD = result.colData;
// colN = result.colNames;
var colM = result.colModel;
//alert(result.colModel);
jQuery("#jsonmap").jqGrid
(
{
jsonReader: { repeatitems: false, cell: "",id: "0" },
//url: "GetData.aspx",
datatype: 'json',
mtype: 'POST',
colModel: colM,
data: colD.rootVar,
ColNames: colN,
ColModel: ColM,
height: "auto",
gridview: true,
pager: '#pager',
rowNum: 5,
rowList: [5, 10, 20, 50],
viewrecords: true,
loadComplete: function (data) {
alert('loaded completely');
},
loadError: function () {
alert('error');
}
});
},
error: function (x, e) {
alert(x.readyState + ' ' + x.status + e.msg);
}
});
The following code should be replaced by ADO.Net connection in GetData.aspx
var list = new Collection<People>
{
new People {Id = 1, Name = "John", Gender = 1, IsClosed = false},
new People {Id = 2, Name = "Abel", Gender = 1, IsClosed = false},
new People {Id = 3, Name = "Aaron", Gender = 1, IsClosed = true},
new People {Id = 4, Name = "Tsion", Gender = 2, IsClosed = true},
new People {Id = 5, Name = "Mussie", Gender = 2, IsClosed = true}
};
Would you please tell me what to do in the next step?
I do have server end data source (SQL server). so should I write a select statement to get the total number of records, pages and order by (sorting) fearures to display in the grid? If so would you please give sample code which has top, limit and order by?
Is there anything missing in the above codes to get the data dynamically?

There are several things wrong with your implementation especially if you want it to be editable but just to load the data you need to fix your column mappings. They do not match. Also, I believe it's case sensitive so you need to change the colNames to below and update colModel to match those names/case:
colNames: ['Id', 'Name','IsClosed','Gender']

Related

Asp.Net MVC jqgrid is not displaying my data

I am trying to fill a jqgrid. The grid is rendered but no data is displayed. I know my controller -- as called through a standard ajax function -- is working. It returns the data I'd expect.
How do I verify that jqgrid is returning the same data and what am I doing incorrectly that is not allowing the data to be dispayed?
jqgrid:
<script type="text/javascript">
jQuery(document).ready(function() {
$.ajaxSetup({ cache: false });
var rvtoken = $("input[name='__RequestVerificationToken']").val();
var ModuleId = #Dnn.ModuleContext.ModuleId;
var TabId = #Dnn.ModuleContext.TabId;
$('#grid').jqGrid({
url: '/DesktopModules/MVC/CW.GridTest/Item/getArtists2',
datatype: 'json',
mtype: 'POST',
contentType: 'application/json',
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader('ModuleId', ModuleId);
jqXHR.setRequestHeader( 'TabId', TabId);
jqXHR.setRequestHeader('RequestVerificationToken', rvtoken);
},
colNames: ['ArtistID', 'ArtistName', 'City'],
colModel: [
{ name: 'ArtistID', index: 'ArtistID', width: 80, align: 'left', editable: false },
{ name: 'Name', index: 'ArtistName', width: 120, align: 'left', editable: true },
{ name: 'Location', index: 'City',width: 60,align: 'left',editable: true}
],
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
loadOnce: true,
autoencode: true,
height: '100%',
rowNum: 10,
emptyrecords: 'No records',
sortname: 'ArtistID',
sortorder: 'desc',
viewrecords: true,
caption: 'Artists',
width: 300,
gridview: true,
jsonReader:
{
total: 'total',
page: 'page',
records: 'records',
root: 'rows',
repeatitems: false,
id: 'ArtistID'
}
});
jQuery("#grid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
});
</script>
<div>
<table id="grid"></table>
<div id="pager"></div>
</div>
Returned data from standard ajax:
{
"total":100,
"page":99,
"records":6,
"rows":"[
{\"ArtistID\":1,\"ArtistName\":\"Clayton Knight\",\"City\":\"Tigard\"},
{\"ArtistID\":2,\"ArtistName\":\"Corral Creek Bluegrass\",\"City\":\"Sherwood\"},
{\"ArtistID\":3,\"ArtistName\":\"Never Strangers Band\",\"City\":\"Portland\"},
{\"ArtistID\":5,\"ArtistName\":\"The Hillwilliams\",\"City\":\"Tigard\"},
{\"ArtistID\":7,\"ArtistName\":\"Bobo and the Bobbettes\",\"City\":\"Ellensburg\"},
{\"ArtistID\":27,\"ArtistName\":\"Bobo 5\",\"City\":\"Ellensburg\"}
]"
}
It was my controller. Not that it wasn't working but that it wasn't returning what I thought it should be. I was deserializing the data table for the "rows" element, and then deserializing the entire element again. So, the controller wasn't return a json string that jqgrid could actually work with.
It's all working now...
public String getArtists2()
{
using (var ac = new ArtistListingController())
{
ac.Gets();
ac.LoadDatatable();
DataView view = new DataView(ac.Datatable);
DataTable dt = view.ToTable(false, "ArtistID", "ArtistName", "City");
var jsonData = new
{
page=1,
total = 1, // (ac.RecordCount + rows - 1) / rows,
records = ac.RecordCount,
rows = dt //JsonConvert.SerializeObject(dt)
};
return JsonConvert.SerializeObject(jsonData);
}
}
Returning:
{
"page":1,
"total":1,
"records":6,
"rows":[
{
"ArtistID":1,
"ArtistName":"Clayton Knight",
"City":"Tigard"
},
{
"ArtistID":2,
"ArtistName":"Corral Creek Bluegrass",
"City":"Sherwood"
},
{
"ArtistID":3,
"ArtistName":"Never Strangers Band",
"City":"Portland"
},
{
"ArtistID":5,
"ArtistName":"The Hillwilliams",
"City":"Tigard"
},
{
"ArtistID":7,
"ArtistName":"Bobo and the Bobbettes",
"City":"Ellensburg"
},
{
"ArtistID":27,
"ArtistName":"Bobo 5",
"City":"Ellensburg"
}
]
}

How to hit JQGrid url in asp.net web form?

I am new in asp.net web form and i am unable to hit the url. Jqgrid is showing but the url to get data is not hitting. This is my aspx content named as emplosyee_list.aspx.
<%# Page Title="" Language="C#" MasterPageFile="~/main.Master" AutoEventWireup="true" CodeBehind="employee_list.aspx.cs" Inherits="CollegeManagementSystem.employee_list" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Content" runat="server">
<div id="page-wrapper">
Back
<div class="container-fluid">
<div class="col-lg-5">
<div>
<span class="headerFont">Employee List</span>
<hr class="lining"/>
</div>
</div>
</div>
</div>
<div >
<table id="grid">
</table>
</div>
<link href="../Content/Site.css" rel="stylesheet" />
<link href="../Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="../Content/StyleSheet1.css" rel="stylesheet" />
<script src="../Scripts/jquery-1.9.1.js"></script>
<script src="../Scripts/jquery-1.9.1.min.js"></script>
<script src="../Scripts/jquery.jqGrid.js"></script>
<script src="../Scripts/jquery.jqGrid.min.js"></script>
<script src="../Scripts/employeeJquery.js"></script>
</asp:Content>
This is my employee_list.aspx.cs
{
public partial class employee_list : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string GetList()
{
var list = GetDataFromDB();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(list);
}
public static List<Dictionary<string, object>> GetDataFromDB()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog='College Management System';Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT username, name, DOB, date, gender,address,mobile,phone,email FROM employee_details ORDER BY username", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
}
}
And this is my Jqgrid code
$("#grid").jqGrid({
url: '/Admin/employee_list.aspx/GetList',
datatype: "json",
colNames: ['User', 'Name', 'DOB', 'Date',
'Gender', 'Address', "Mobile", 'Phone', 'Email', ],
colModel: [
{ name: 'User', index: 'User', width: 50, stype: 'text' },
{ name: 'Name', index: 'Name', width: 150 },
{ name: 'DOB', index: 'DOB', width: 100 },
{ name: 'Date', index: 'Date', width: 80, align: "right" },
{ name: 'Gender', index: 'Gender', width: 80, align: "right" },
{ name: 'Address', index: 'Address', width: 80, align: "right" },
{ name: 'Mobile', index: 'Mobile', width: 150, sortable: false },
{ name: 'Phone', index: 'Phone', width: 100, sortable: false },
{ name: 'Email', index: 'Email', width: 150, sortable: false }
],
pager: { enable: true, limit: 5, sizes: [2, 5, 10, 20] },
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
viewrecords: true,
pager :'#gridpager',
sortorder: "desc",
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
caption: "List Employee Details"
});
The url is not hiting and there is no error on consoleWhat is the problem
I see the following errors in your code:
you should include jQuery UI CSS on the HTML page. You can use for example <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css" rel="stylesheet" />
you can't include both minimized and non-minimized versions on the same page. So you should remove, for example, the references to non-minimized files jquery-1.9.1.js and jquery.jqGrid.js.
you should include the reference to i18n/grid.locale-en.js (or other locale file) before jquery.jqGrid.min.js.
You should remove from GetList() the line JavaScriptSerializer serializer = new JavaScriptSerializer(); and the call of serializer.Serialize. Instead of that the WebMethod should return object. The dot net framework will serialize the object to JSON or XML based on the contentType of HTTP request. The code of GetList method could look like
[WebMethod]
public object GetList()
{
return GetDataFromDB();
}
you should include in the option of jqGrid the following:
mtype: 'POST',
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
jsonReader: {
root: function (obj) {
// after the fix of WebMethod the next line
// can be reduced to
// return obj.d;
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
repeatitems: false
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
height: "auto",
gridview: true
Moreover the value of pager parameter seems be wrong. You don't wrote which version of jqGrid you use and which fork (). I don't know specific options of Guriddo jqGrid JS, but in case of usage free jqGrid or old jqGrid in version <= 4.7, the pager parameter have wrong value.
I recommend you to remove all index properties from colModel.

jqgrid not displaying, mvc 3

I am using asp.net MVC 3 , and my table is not displayed.
Then I had built another project, but in MVC 4. Everything worked fine.
My Controller code:
public JsonResult GetTodoLists(string sidx, string sord, int page, int rows, Billboard billboard) //Gets the todo Lists.
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var todoListsResults = db.billboard.Select(
a => new
{
a.BillboardID,
a.Event_date,
a.Event_name,
});
int totalRecords = todoListsResults.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
todoListsResults = todoListsResults.OrderByDescending(s => s.Event_name);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
todoListsResults = todoListsResults.OrderBy(s => s.Event_name);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = todoListsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
My View code:
<h2>Todo List</h2>
<div>
<table id="grid"></table>
<div id="pager"></div>
</div>
<head>
<title>jqGrid</title>
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-ru.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/Billboard.js"></script>
</head>
And my js code:
jQuery(document).ready(function () {
$("#grid").jqGrid({
url: "/Home/GetTodoLists",
datatype: 'json',
mtype: 'Get',
colNames: ['BillboardID', 'Event_date', 'Event_name', ],
colModel: [
{ key: true, hidden: true, name: 'BillboardID', index: 'BillboardID', editable: true },
{ key: false, name: 'Event_date', index: 'Event_date', width: 80, editable: true, },
{ key: false, name: 'Event_name', index: 'Event_name', editable: true, editrules: true },
],
pager: jQuery('#pager'),
rowNum: 5,
rowList: [5, 10, 15],
height: '20%',
viewrecords: true,
caption: 'Афиша',
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
autowidth: true,
multiselect: false,
}).navGrid('#pager', { edit: false, add: true, del: true, search: true, refresh: true },
{
// edit options
zIndex: 100,
url: '/Home/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// add options
zIndex: 100,
url: "/Home/Create",
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// delete options
zIndex: 100,
url: "/Home/Delete",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
What is the problem ? Where am I wrong?
Problem was solved.
Change this:
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-ru.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/Billboard.js"></script>
on:
<link href="#Url.Content("~/Content/jquery.jqGrid/ui.jqgrid.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" />
<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.10.4.min.js")"></script>
<script src="#Url.Content("~/Scripts/i18n/grid.locale-en.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.jqGrid.min.js")"></script>
<script src="#Url.Content("~/Scripts/Billboard.js")"></script>

Binding json with flexigrid in ASP.NET

I am using a flexigrid in ASP.NET, I am having trouble binding the JSON data with the flexigrid I get the JSOn response from the web service but it doesn't bind with the grid and doesn't display the grid, Where am I wrong. I am using a webservice to return the JSON data , Here is the code which I am using.Thanks.
My js function to get data from the webservice and bind the json with flexigrid
$(document).ready(function () {
var obj;
$.ajax({
type: "post",
contentType: "application/json",
url: "FlexService.asmx/GetData",
data: "{}",
dataType: 'json',
success: function (result) {
obj = $.parseJSON(result.d);
//add data
$("#FlexTable").flexAddData(formatEmployeeResults(obj));
}
});
//init flexigrid
$("#FlexTable").flexigrid({
dataType: 'json',
colModel: [{display: 'ID', name: 'id', width: 90, sortable: true, align: 'center'},
{display: 'First Name', name: 'fName', width: 120, sortable: true,align: 'left'},
{display: 'Last Name', name: 'lName', width: 120, sortable: true, align: 'left'},
{display: 'Role', name: 'uRole', width: 120, sortable: true, align: 'left'},
{display: 'Salary', name: 'sal', width: 80, sortable: true, align: 'left'}],
searchitems: [{display: 'ID', name: 'id'},
{display: 'First Name', name: 'fName', isdefault: true}],
sortname: "ID",
sortorder: "asc",
usepager: true,
title: 'Employees',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 750,
height: 200
});
function formatEmployeeResults(Employee) {
var rows = Array();
for (i = 0; i < Employee.length; i++) {
var item = Employee[i];
rows.push({ cell: [item.id, item.fName, item.lName, item.uRole, item.sal]
});
}
return {total: Employee.length, page: 1, rows: rows}
}
});
My web service code :
public string GetData()
{
List<Employee> lst = new List<Employee>();
string strConn = ConfigurationManager.ConnectionStrings["FlexDb"].ConnectionString;
OleDbConnection cnx = new OleDbConnection(strConn);
OleDbCommand cmd = new OleDbCommand("Flex",cnx);
cnx.Open();
cmd.CommandType = CommandType.StoredProcedure;
OleDbDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Employee e1 = new Employee();
e1.id = Convert.ToInt32(dataReader["USER_ID"]);
e1.fName = dataReader["FIRST_NAME"].ToString();
e1.lName = dataReader["LAST_NAME"].ToString();
e1.uRole = dataReader["USER_ROLE"].ToString();
e1.sal = dataReader["SALARY"].ToString();
lst.Add(e1);
}
var jss = new JavaScriptSerializer();
return jss.Serialize(lst);
}
I tried your example, and it works perfectly. The only thing is that you might have forgotten to add the CSS file link in your head tag. For example:
<link href="Content/flexigrid/flexigrid.css" rel="stylesheet" />

Not able to Add row using JQGrid

Here is the JQGrid setup information
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/TabMaster/GetGridData',
datatype: 'json',
mtype: 'GET',
colNames: ['col ID', 'First Name', 'Last Name'],
colModel: [
{ name: 'colID', index: 'colID', width: 100, align: 'left' },
{ name: 'FirstName', index: 'FirstName', width: 150, align: 'left', editable: true },
{ name: 'LastName', index: 'LastName', width: 300, align: 'left', editable: true },
],
pager: jQuery('#pager'),
rowNum: 4,
rowList: [1, 2, 4, 5, 10],
sortname: 'colID',
sortorder: "asc",
viewrecords: true,
multiselect: true,
imgpath: '/scripts/themes/steel/images',
caption: 'Tab Master Information'
}).navGrid('#pager', { edit: true, add: true, del: true },
// Edit options
{
savekey: [true, 13],
reloadAfterSubmit: true,
jqModal: false,
closeOnEscape: true,
closeAfterEdit: true,
url: "/TabMaster/Edit/",
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Company successfully updated");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Add options
{},
// Delete options
{url: '/TabMaster/Remove' }
);
});
following is the details for Getting Data and Update Data using JQGrid
#region "JQGrid Actions"
public JsonResult GetGridData(string sidx, string sord, int rows, int page)
{
int pageIndex = page;
int totalRecords = Convert.ToInt32(_tabmasterService.Count());
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
IQueryable<TabMasterViewModel> tabmasters = _tabmasterService.GetQueryTabMasterList(sidx, sord, rows, page);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from tm in tabmasters
select new
{
id = tm.colID,
cell = new string[] { tm.colID.ToString(), tm.FirstName, tm.LastName }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection updateExisting)
{
int _id = Convert.ToInt32(updateExisting["colID"]);
TabMasterViewModel editExisting = new TabMasterViewModel();
editExisting = _tabmasterService.GetSingle(x => x.colID == id);
try
{
UpdateModel(editExisting);
_tabmasterService.Update(editExisting);
return Content("Success");
}
catch (Exception e)
{
return Content(e.Message);
}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Remove(string id)
{
List<String> ids = new List<String>(id.Split(','));
for (int i = 0; i < ids.Count; i++)
{
int deleteid = Convert.ToInt32(ids[i]);
TabMasterViewModel deleteExisting = new TabMasterViewModel();
deleteExisting = _tabmasterService.GetSingle(x => x.colID == deleteid);
_tabmasterService.Delete(deleteExisting);
}
return RedirectToAction("Index");
}
#endregion
Note:- Get and Update is successfully working but i have problem in ADD and DELETE.
Please anybody help me to write the function for ADD and DELETE?
Here is the complete solution for ADD, EDIT and DELETE
*index.cshtml*
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/TabMaster/GetGridData',
datatype: 'json',
mtype: 'GET',
colNames: ['col ID', 'First Name', 'Last Name'],
colModel: [
{ name: 'colID', index: 'colID', width: 100, align: 'left', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{ name: 'FirstName', index: 'FirstName', width: 150, align: 'left', editable: true },
{ name: 'LastName', index: 'LastName', width: 300, align: 'left', editable: true },
],
pager: jQuery('#pager'),
rowNum: 4,
rowList: [1, 2, 4, 5, 10],
sortname: 'colID',
sortorder: "asc",
viewrecords: true,
multiselect: true,
imgpath: '/scripts/themes/steel/images',
caption: 'Tab Master Information'
}).navGrid('#pager', { edit: true, add: true, del: true },
// Edit options
{
savekey: [true, 13],
reloadAfterSubmit: true,
jqModal: false,
closeOnEscape: true,
closeAfterEdit: true,
url: "/TabMaster/Edit/",
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Company successfully updated");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Add options
{url: '/TabMaster/Create', closeAfterAdd: true },
// Delete options
{url: '/TabMaster/Remove' },
{ closeOnEscape: true, multipleSearch: true,
closeAfterSearch: true
}
);
});
controller.cs
#region "JQGrid Actions"
public JsonResult GetGridData(string sidx, string sord, int rows, int page)
{
int pageIndex = page;
int totalRecords = Convert.ToInt32(_tabmasterService.Count());
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
IQueryable<TabMasterViewModel> tabmasters = _tabmasterService.GetQueryTabMasterList(sidx, sord, rows, page);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from tm in tabmasters
select new
{
id = tm.colID,
cell = new string[] { tm.colID.ToString(), tm.FirstName, tm.LastName }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection updateExisting)
{
int _id = Convert.ToInt32(updateExisting["colID"]);
TabMasterViewModel editExisting = new TabMasterViewModel();
editExisting = _tabmasterService.GetSingle(x => x.colID == id);
try
{
UpdateModel(editExisting);
_tabmasterService.Update(editExisting);
return Content("Success");
}
catch (Exception e)
{
return Content(e.Message);
}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Remove(string id)
{
List<String> ids = new List<String>(id.Split(','));
for (int i = 0; i < ids.Count; i++)
{
int deleteid = Convert.ToInt32(ids[i]);
TabMasterViewModel deleteExisting = new TabMasterViewModel();
deleteExisting = _tabmasterService.GetSingle(x => x.colID == deleteid);
_tabmasterService.Delete(deleteExisting);
}
return RedirectToAction("Index");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection FormValue)
{
if (ModelState.IsValid)
{
TabMasterViewModel addNew = new TabMasterViewModel();
addNew.FirstName = FormValue["FirstName"];
addNew.LastName = FormValue["LastName"];
_tabmasterService.Add(addNew);
}
return RedirectToAction("Index");
}
#endregion

Resources