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

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.

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"
}
]
}

JQgrid is not working in MVC4 and EntityFramework

Hi I started working on JQGrid, I followed the post which I got from an internet blog Jqgrid with MVC
My Code Looks like this:
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<ol class="round">
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData',
datatype: 'json',
mtype: 'POST',
colNames: ['UserId', 'FirstName', 'LastName', 'CreatedBy', 'Designation', 'City'],
colModel: [
{ name: 'UserId', index: 'UserId', width: 40, align: 'left' },
{ name: 'FirstName', index: 'FirstName', width: 40, align: 'left' },
{ name: 'LastName', index: 'LastName', width: 400, align: 'left' },
{ name: 'CreatedBy', index: 'CreatedBy', width: 400, align: 'left' },
{ name: 'Designation', index: 'Designation', width: 400, align: 'left' },
{ name: 'City', index: 'City', width: 400, aligh: 'left' }],
pager: jQuery('#pager'),
rowNum: 2,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/content/images',
caption: 'My first grid'
});
});
</script>
<%-- HTML Required--%>
<h2>My Grid Data</h2>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
</ol>
}
And my Controller looks like this:
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Expressions;
using UserInfoGrid.Models;
using System.Linq;
using System.Linq.Dynamic;
namespace UserInfoGrid.Controllers
{
public class HomeController : Controller
{
UserInfoEntities db = new UserInfoEntities();
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = db.Users.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// var userInfo = db.User(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
//var userInfo = db.Users.OrderBy((sidx+""+sord).Skip(pageIndex * pageSize).Take(pageSize)).ToList();
var userInfo = db.Users.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from u in userInfo
select new
{
i = u.UserId,
cell = new string[] { u.UserId.ToString(), u.FirstName, u.LastName, u.CreatedBy.ToString(), u.Designation, u.City.ToString() }
//cell = new string[] { "", "", "", "" }
}).ToArray()
};
return Json(jsonData);
}
}
}
}
The problem is, nothing is displaying in Index page. I am tired of trying, please help me. If you find any flaws in my code.
Thanks in advance
Please try is as below.
[HttpPost]
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
//your code here
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
Change this url: '/Home/DynamicGridData' to this url: '#Url.Action("DynamicGridData")'

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" />

Binding database with kendo UI grid in ASP.NET MVC

I am trying to implement KendoUI Grid control in my ASP.NET MVC application.
I know KendoUI guys have given numerous examples but its not working for me.
My Model code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
namespace KendoGrid.Models
{
public class status
{
public string SiteId { get; set; }
public string SiteName { get; set; }
public string SiteStatus { get; set; }
public static List<status> StatusInfo()
{
SqlConnection sconn = new SqlConnection(#"Data Source=DS-7071BC8FDEE6\SQLEXPRESS;Initial Catalog=AmanoTest;User ID=sa;Password=india#123");
SqlCommand cmd = new SqlCommand("select * from SiteMaster", sconn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
status cstat;
List<status> statlist = new List<status>();
foreach (DataRow dr1 in dt.Rows)
{
cstat = new status();
cstat.SiteId = dr1[0].ToString();
cstat.SiteName = dr1[1].ToString();
cstat.SiteStatus = dr1[2].ToString();
statlist.Add(cstat);
}
return statlist;
}
}
}
My Controller Code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KendoGrid.Models;
using Kendo.Mvc.UI;
namespace KendoGrid.Controllers
{
public class statusController : Controller
{
//
// GET: /status/
public ActionResult Index()
{
return View();
}
public ActionResult Site()
{
//List<status> status = status.GetStatus();
List<status> temp = status.StatusInfo();
ViewData["table"] = temp;
return View();
}
}
}
And my view (.cshtml page) is:
#model KendoGrid.Models.status
#using Kendo.Mvc.UI
#*#{
Layout = null;
}
*#
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Site</title>
</head>
<body>
<div>
#(Html.Kendo().Grid(Model)()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.siteID);
columns.Bound(p => p.siteID);
columns.Bound(p => p.siteID);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
)
</div>
</body>
</html>
On executing it says :
The best overloaded method match for
'Kendo.Mvc.UI.Fluent.WidgetFactory.Grid(System.Data.DataTable)' has
some invalid arguments
Look like you are missing couple step here. Please go through this step n this might resolve your problem
http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
You can use
var url = "/DesktopModules/MyServices/API/ATSManageClient/GetAllProjectsTechnologyBased?PortalId=210&tabid=95&Technology=" + selectedplatform;
var element = $("#grid").kendoGrid({
//debugger;
type: "odata",
dataSource: {
transport: {
read: url
},
schema: {
model: {
fields: {
RecievedDate: { type: "date" }
}
}
},
pageSize: 100
},
columnMenu: true,
scrollable: true,
filterable: true,
resizable: true,
sortable: true,
detailTemplate: kendo.template($("#template").html()),
detailInit: detailInit,
dataBound: function () {
},
columns: [
{
field: "ProjectID",
title: "Action",
template: "<a href='/Dashboard/Communication?ProjectID=#=ProjectID#'>View Communication</a>",
width: "20%"
},
//s debugger;
{
field: "ClientName",
width: "20%",
title: "Client",
template: "<a href='Accounts/UpdateClient.aspx?ClientId=#=ClientID#'> #= ClientName #</a>",
attributes: {
title: "#=ClientName#"
}
},
{
field: "ProjectTitle",
width: "20%",
title: "Project",
template: "<a href='Project/EditProject.aspx?ProjectID=#=ProjectID#'> #= ProjectTitle #</a>",
attributes: {
title: "#=ProjectTitle#"
}
},
{
field: "ColorList",
width: "20%",
template: kendo.template($("#template2").html()),
title: "Status"
},
{
field: "RecievedDate",
width: "20%",
title: "Check List Status",
template: ""
},
{
field: "RecievedDate",
width: "20%",
title: "Opened Bugs",
template: ""
}
],
pageable: {
// we don't set any DataSource here
pageSizes: [100, 150, 200]
}
});

jqgrid implementation using JSOn and 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']

Resources