I am new to JQGrid and JQUery please give me the solution?
I am developing the Sharepoint application2010 in that am using the JQGrid, i want to show the list data in the JQGrid. for this i have the dataset, using the dataset i need to bind the JQGrid, that dataset having differnet columns.
when ever we using the Noraml asp.net Gridview we can give the datasource directly like below no need to mention columns, in the same way i need to develop the JQGrid.
<asp:Gridview runat="server" id="GvSample"/>
in .cs
GVSample.datasource=ds;
gvSample.databind();
please help!
You can see the sample of JQGrid in asp.net here. It shows how to bind data source and column to JQGrid.
http://www.trirand.net/demoaspnet.aspx
Firs get the details about the columns and then bind.
put this in the document.ready
$.ajax(
{
type: "POST",
url: "SomeUrl/GetColumnsAndData",
data: "",
dataType: "json",
success: function(result)
{
colD = result.colData;
colN = result.colNames;
colM = result.colModel;
jQuery("#list").jqGrid({
jsonReader : {
cell: "",
id: "0"
},
url: 'SomeUrl/Getdata',
datatype: 'jsonstring',
mtype: 'POST',
datastr : colD,
colNames:colN,
colModel :colM,
pager: jQuery('#pager'),
rowNum: 5,
rowList: [5, 10, 20, 50],
viewrecords: true
})
},
error: function(x, e)
{
alert(x.readyState + " "+ x.status +" "+ e.msg);
}
});
setTimeout(function() {$("#list").jqGrid('setGridParam',{datatype:'json'}); },50);
Related
I have being trying to populate list of data in a grid for this purpose I have used JqGrid. I have installed jqGrid plugin from nuget manager and from online tutorial I have been trying to implement the same.
This is what I have done so far:-
View:-
<h2>Search</h2>
<div class="container">
<div class="row">
<table id="tblRecruiterGrid"></table>
<div id="dvPagination"></div>
</div>
</div>
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-grid.locale-en.js"></script>
<script src="~/Scripts/jquery.jqGrid.js"></script>
<script src="~/Scripts/recruiter.js"></script>
Controller:-
public ActionResult RecruiterGridData(string sidx = "", string sord = "", int page = 1, int rows = 10)
{
var vData = recruiterRepo.GetAllByRelation();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = vData.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
switch (sidx)
{
case "RID":
vData = sord == "desc"
? vData.OrderByDescending(x => x.RecruiterID).ToList()
: vData.OrderBy(x => x.RecruiterID).ToList();
break;
default:
vData = sord == "desc"
? vData.OrderByDescending(x => x.RecruiterID).ToList()
: vData.OrderBy(x => x.RecruiterID).ToList();
break;
}
var vResult = vData.Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = vResult.Select(x => new
{
RID = x.RecruiterID,
RecruiterName = x.RecruiterName,
Email = x.Email,
CompanyName = x.CompanyName,
Designation = x.Designation,
Mobile = x.Mobile
}).ToList()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Javascript:-
$(function () {
$('#tblRecruiterGrid').jqGrid({
url: "/Recruiter/RecruiterGridData/",
datatype: 'json',
mtype: 'get',
colNames: ['RID', 'Recruiter Name', 'Email', 'Company Name', 'Designation', 'Mobile'],
colModel: [{ key: true, hidden: true, name: 'RID' },
{ key: false, hidden: false, name: 'RecruiterName' },
{ key: false, hidden: false, name: 'Email' },
{ key: false, hidden: false, name: 'CompanyName' },
{ key: false, hidden: false, name: 'Designation' },
{ key: false, hidden: false, name: 'Mobile' }],
pager: '#dvPagination',
rowNum: 10,
rowList: [5, 10, 25, 50, 100],
sortname: 'RID',
sortorder: "asc",
height: 'auto',
gridview: true,
autoencode: true,
viewrecords: true,
caption: '',
emptyrecords: 'No records to display',
jsonReader: { repeatitems: false, id: 'RID' },
autowidth: true,
multiselect: false,
});
});
I'm being able to populate data in jqGrid but the paging is causing a problem. In browser developer console I'm getting a undefined error because of which the paging is not loading properly. I tried to search the problem in google but every result section pointed to include missing jqGrid file grid.locale-en.js which I have already included in my view some suggested to check if grid.locale-en.js is loaded before jquery.jqGrid.js so when I tracked down in network I got following result.
After doing lots of R&D I'm still not been able to resolve following error:-
Uncaught TypeError: Cannot read property 'integer' of undefined
Note:- Jquery libraries has already been defined in layout head section.
Please include always the exact version number of jqGrid, which you use, and the information about the fork of jqGrid (free jqGrid, Guriddo jqGrid JS or an old jqGrid in version <=4.7), which you use.
I suppose that you use some old version of jqGrid and you just used wrong name for locale (localization) file. The file name jquery-grid.locale-en.js is very suspected. The distribution of jqGrid have i18n with the file grid.locale-en.js. The usage of old jqGrid without locale file can produce the error Cannot read property 'integer' of undefined during filling the pager of jqGrid.
Another important error in your code is the usage of key: true property for more as one column. The column have to have unique values in every row. The property key: true informs jqGrid to use the contains from the column instead of the id property. You used already the option jsonReader: { repeatitems: false, id: 'RID' } which informs to use RID property of items as the rowid. This I would recommend you to remove unneeded hidden RID column from colModel and remove key: true, hidden: false from all other columns. You can remove options with default values: mtype: 'get', sortorder: "asc", caption: '' and multiselect: false.
I would recommend you to try to use free jqGrid, it's the fork of jqGrid, which I develop after Tony Tomov have changed the licence agreement of jqGrid and it's name to Guriddo jqGrid JS (see the post). Many new features, which
I implemented in free jqGrid are described in the wiki and readmes to all versions currently published.
net webforms application.
In my .aspx page Im using jQuery datatables and its gets data using ajax.
In my jQuery datatables I have some configuration for setting up my columns:
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'className': 'dt-body-center',
'render': function(data, type, full, meta) {
//return '<input type="checkbox">';
if (data == "false") {
return '<input type="checkbox" class="styled green">';
} else {
return '<input type="checkbox" class="styled green" checked="' + data + '">';
}
}
}],
I have a requirement to move this jQuery datatable to an usercontrol so it can be reusable on other parts of the web application but I should be able to let the control know what columns to hide.
I was thinking on sending from server other property in my json, an array maybe named HideCols that has the index of the columns that I want to hide and then apply with jQuery some code to hide them.
Im getting the table data like this:
"fnServerData": function(sSource, aoData, fnCallback) {
aoData.push(
{ name: "filter", value: filterVal }
);
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success": function(msg) {
// here I get my json table data from server
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
// here I can do my jQuery code to hide columns
if(json.HideCols != null)
{
}
}
});
}
Other way would be great if I can send from server the columnDefs configuration but I guess its going to be more tricky.
Any clue?
I have implemented the dynamic columnDefs (colModel) functionality with jqGrid. You may read the post here jqgrid-dynamic-reading-of-colmodel-and-colnames-from-codebehind-of-aspx
You may get the basic idea of generating dynamic columnDefs (xxx_colModel in above post) and ajaxData (xxx_Data in above post) from code-behind and implement it in your way. Set properties of columns to hide in the dynamically generated columnDefs.
As regard to your approach of hiding the columns:
I was thinking on sending from server other property in my json, an array maybe named HideCols that has the index of the columns that I want to hide and then apply with jQuery some code to hide them.
You may add another property to top level of JSON along with xxx_colModel and xxx_Data say xxx_HiddenCols and store csv column IDs e.g. 2,8,9
Then on the client side, after the grid is initialized, you may use for loop to process each column to hide e.g.
var colArray = xxx_HiddenCols.split(',');
for (var i = 0; i < colArray.length; i++) {
table.column( colArray[i] ).visible( false );
}
I am new to using jqGrid and jquery.I am not able to bind my json data which I retrive from the webmethod onto the jqGrid.
I have also used firebug to cross verify and i am receiving data from it. Some help regarding this will be great. I would aslo like to know if any other references needs to be added.
following is the code that I have implemented.
PAGE METHOD
[WebMethod]
public static string GetData()
{
Customer Cone = new Customer();
Customer Ctwo = new Customer();
Cone.CustomerID = "100";
Cone.CustomerName = "abc";
Ctwo.CustomerID = "101";
Ctwo.CustomerName = "xyz";
List<Customer> lstCustomer = new List<Customer>();
lstCustomer.Add(Ctwo);
lstCustomer.Add(Cone);
JavaScriptSerializer jsonSerz = new JavaScriptSerializer();
string serializedData = jsonSerz.Serialize(lstCustomer);
return serializedData;
}
client side coding
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="jquery.jqGrid.min.js"></script>
<script type="text/javascript">
function GetData() {
alert('Inside GetData');
var data = PageMethods.GetData(OnSuccess, OnFailed);
}
function OnFailed(error) {
alert('Failed');
alert(error.get_message());
}
function OnSuccess(data) {
alert(data);
}
$(document).ready(function() {
$('#submit').click(function() {
alert('Button Clicked');
$('#list').jqGrid({
url: 'http://localhost:1405/WebSite1/Default.aspx/GetData',
data: '{}', // For empty input data use "{}",
dataType: 'local',
type: 'POST',
contentType: "application/json; charset=utf-8",
colNames: ['CustomerID', 'CustomerName'],
colModel: [
{ name: 'CustomerID', index: 'CustomerID', width: 80,
align: 'left', editable: false },
{ name: 'CustomerName', index: 'CustomerName', width: 120,
align: 'left', editable: true}],
pager: $('#pager'),
rowNum: 5,
rowList: [10],
sortname: 'CustomerID',
sortorder: 'desc',
viewrecords: true,
width: 300
});
});
});
</script>
AND HTML code
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<input type="button" id="submit" value="Fetch" title="Fetch"
onclick="javascript:GetData()" />
<table id="list">
</table>
<div id="pager">
</div>
First of all I recommend you to play a little with another working code which you can download here (see more information here). More links to another examples you can find here.
I try to describe some problems in your current code.
You use 'http://localhost:1405/WebSite1/Default.aspx/GetData' as the url. You shold better use only pathes like '/WebSite1/Default.aspx/GetData' or 'WebSite1/Default.aspx/GetData' or you can easy receive same origin policy problem.
You should use ASMX service instead of placing the code inside of ASPX page (Default.aspx/GetData). You should just add new item to your ASP.NET solution and choose Web Serice template. The corresponding code template will be added for you and web.config will be modified. In the same way you can place WCF service inside your ASP.NET project. The step is independ on the technology which you use (WebForms, ASP.NET MVC and so on).
Instead of manual JSON serialisation with respect of JavaScriptSerializer you should define [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attriute to your method and return an object from the web method (like List<Customer> in your case). The JSON serialization will be done automatically for you.
You use dataType: 'local' which is wrong parameter for jqGrid. Correct parameter will be datatype:'json' (datatype instead of dataType and 'json' to make the request to the server).
Instead of type: 'POST' you should use mtype: 'POST'.
Instead of contentType: "application/json; charset=utf-8" you should use ajaxGridOptions: { contentType: "application/json" }.
The usage of data: '{}' is also wrong. Probably you try to use data parameter of jQuery.ajax like with dataType parameter. In jqGrid you should use pastData instead of data and the data parameter must be an array and has another meaning. I recommand you to look at the code of the example (see reference at the begin of my answer).
You should not place $('#list').jqGrid({...}); inside of click handle. The problem is that the code make some initializations of jqgrid and then fill the grid. What you probaly want is creating the grid only once and then refreshing it with another input data probaby (I am not sure that it is so). So you should move $('#list').jqGrid({...}); inside of $(document).ready(function() {...};. If needed you can use $('#list').trigger("reloadGrid") inside of the click event handle. Alternatively you can use GridUnload to destroy the existing grid before creating it new.
I can continue, but my main recommendation is to examine another examples and use ASMX or WCF service which provide the data for jqGrid.
Entire grid binding event is called before your page method.
You have put it under document.Ready event. Try calling it from the button click event.
I am not sure but there should be some way to bind json data to Jquery grid on client side without using the URL part.
try mapping "data:" to some Json value.
I am having a lot of trouble binding my Json data to a JqGrid.
In my Default.aspx.cs I have the following method :
[WebMethod]
public static string GetData()
{
CustomerHelper C = new CustomerHelper();
var data = C.GetAllCustomersSerialized();
return data;
}
The C.GetAllCustomersSerialized(); method returns
return JsonConvert.SerializeObject(customersList); from the CustomerHelper Class.
So basically I am returning serialized data as a string. Hope I am right till this point.
Now my Default.aspx is like so :
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript">
$(document).ready(function() {
$("#Grid1").jqGrid(
{
url: "Default.aspx/GetData",
data: "{}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8;",
colNames: ['Customer Number', 'Customer Name'],
colModel: [
{ name: 'CUSNUM', index: 'CUSNUM', width: 80, align: 'left', jsonmap: 'CUSNUM' },
{ name: 'CO_NAM', index: 'CO_NAM', width: 80, align: 'left', jsonmap: 'CO_NAM' }
],
pager: $("#Pager1"),
rowNum: 20,
rowList: [10, 20, 30, 40, 50],
sortname: 'cusnum',
viewrecords: true,
caption: 'Customers List'
});
});
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table id="Grid1">
</table>
<div id="Pager1">
</div>
</asp:Content>
I have a break point for the GetData() method in the code-behind but it is not being hit. All I get is an empty page with only the headers and the pagesize selection dropdown.
I lookedup all the different questions here which are similar to this, including
jqGrid and dynamic column binding but it doesn't work for me.
Please help.
Well, its been a while and there was no headway made with jqGrid, so I dumped it and used JTemplates instead.
The jqGrid has been kicking my butt (as well as others on this site). I can't seem to get the JSON data from the webservice to load into the jqGrid when using the addJSONData method.
Does anyone know if this is possible to do? I am not using MVC just a plain WebProject webservice in ASP.NET 3.5.
I am using the latest version of jqGrid 3.5.
I don't know what to do. I am currently trying to load just 1 row that I am returning a string in my WS like this:
"Page:1,Total:1,Records:1,Rows:[name: Jeff V title: Programmer]"
Which is then passed into my javascript as:
{"d":"Page:1,Total:1,Records:1,Rows:[name: Jeff Vaccaro title: Programmer]"}
My jQuery code is the following:
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
datatype: processrequest,
mtype: 'POST',
colNames: ['Name', 'Title'],
colModel: [
{ name: 'name', index: 'name', width: 55 },
{ name: 'title', index: 'title', width: 90 }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
sortorder: "desc",
viewrecords: true,
imgpath: 'themes/basic/images',
caption: 'My first grid'
});
});
function processrequest(postdata) {
$(".loading").show();
$.ajax({
type: "POST",
data: "{}",
datatype: "clientside",
url: "../webServices/myTestWS.asmx/testMethod",
contentType: "application/json; charset-utf-8",
complete: function (jsondata, stat) {
if (stat == "success") {
jQuery("#list")[0].addJSONData(eval("(" + jsondata.responseText + ")"));
$(".loading").hide();
} else {
$(".loading").hide();
alert("Error with AJAX callback");
}
}
});
}
I've tried all sorts of different variations of the addJSONData code. Does anyone know if this is possible to do?
Any help is appreciated!
Thanks
First of all your web service should return a class instance with properties page, total, records, rows and so on. If web method has attribute [ScriptMethod (ResponseFormat = ResponseFormat.Json)] the class instance will be correct converted to the the JSON data.
You can use ajaxGridOptions: { contentType: 'application/json; charset=utf-8' } parameter and jsonReader (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data) to load data in the jqGrid. Information from Jqgrid 3.7 does not show rows in internet explorer and Best way to change jqGrid rowNum from ALL to -1 before pass to a web service could be helpful for you.
At the end imgpath is no more supported in version 3.5 of jqGrid.