JSON data is not displaying in JQGrid - c#

I have looked at played around with suggestions in all related answers but to no avail. I tried all kinds of options but again to no avail. I am using ASP.NET with C# as the processing language, and Oracle 10g as a database engine.
Here is my .aspx file:
<form id="LocalizationSearch" name="locSearch" defaultbutton="updateButton" runat="server">
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
var createLanguageList = function () {
$("#list").jqGrid({
url: "KPHandler.ashx?langname=English",
datatype: "json",
contentType: "application/json; charset=utf-8",
mtype: 'POST',
//datatype: "local",
//data: mydata,
autowidth: true,
height: 150,
colNames: ['DelLanguageID', 'DocRecID', 'LanguageID', 'DocPartNumber,', 'NewLanguage', 'ConcentraIDLang', 'ActFromTranslation'],
colModel: [
{ name: 'DelLanguageID', index: 'DelLanguageID', width: 65, editable: false },
{ name: 'DocRecID', index: 'DocRecID', width: 65, editable: false },
{ name: 'LanguageID', index: 'LanguageID', width: 65, editable: false },
{ name: 'DocPartNmbr', index: 'DocPartNmbr', width: 65, editable: true },
{ name: 'NewLanguage', index: 'NewLanguage', editable: true, edittype: 'checkbox', editoptions: { value: "1:0"} },
{ name: 'ConcentraIDLang', index: 'ConcentraIDLang', width: 65, editable: true },
{ name: 'ActFromTranslation', index: 'ActFromTranslation', width: 120, editable: true }
],
rowNum: 5,
rowList: [10, 20, 30],
pager: '#pager',
sortname: 'DelLanguageID',
viewrecords: true,
//altRows: true,
//sortorder: "desc",
caption: "Deliverable Languages",
//height: "100%",
loadonce: true,
gridview: true,
autoencode: true,
loadError: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + errorThrown + jqXHR.responseText);
}
}); // JQGrid
}; // Create function
$("#btnLanguages").click(function () {
createLanguageList();
});
}); // document ready
</script>
<table cellspacing="1" cellpadding="0" width="100%">
<tr>
<td valign="top">
<table id="list"></table>
<div id="pager"></div>
</td>
</tr>
</table>
<input type="button" id="btnLanguages" value="Work With Languages" />
</form>
and here is my C# code that builds the JSON object:
<%# WebHandler Language="C#" Class="KPHandler" %>
using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Configuration;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OracleClient;
public class KPHandler : IHttpHandler
{
private DKCL.ReportDK Rpt = new DKCL.ReportDK();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
System.Collections.Specialized.NameValueCollection forms = context.Request.Form;
string strOperation = forms.Get("oper");
switch (strOperation)
{
case null: // means this is the first time load
string strSQL = "SELECT DelLanguageID, DocRecID, LanguageID, DocPartNmbr, NewLanguage, " +
"ConcentraIDLang, ActFromTranslation FROM DELLANGUAGES WHERE DOCRECID = 18787";
DataTable dlLanguages = Rpt.GetDataTable(strSQL);
context.Response.Write(GetJson(dlLanguages));
break;
default:
break;
} // End Switch
}
// This is generic function that converts DataTable into JSON object.
public string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
public bool IsReusable
{
get
{
return false;
}
}
}
and here is the JSON data returned by the above code (I actually got this as shown by Fiddler2), and my own debugging the code.:
[{"DELLANGUAGEID":"4613","DOCRECID":"18787","LANGUAGEID":"12","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":"c02609839","ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"4614","DOCRECID":"18787","LANGUAGEID":"34","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":null,"ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"4615","DOCRECID":"18787","LANGUAGEID":"1","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":"c02606925","ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"4616","DOCRECID":"18787","LANGUAGEID":"13","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":"c02609850","ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"4617","DOCRECID":"18787","LANGUAGEID":"11","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":"c02606924","ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"4618","DOCRECID":"18787","LANGUAGEID":"3","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":"c02606920","ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"4619","DOCRECID":"18787","LANGUAGEID":"21","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":null,"ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"39703","DOCRECID":"18787","LANGUAGEID":"142","DOCPARTNMBR":"593957-001","NEWLANGUAGE":0,"CONCENTRAIDLANG":null,"ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"89446","DOCRECID":"18787","LANGUAGEID":"161","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":null,"ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"97174","DOCRECID":"18787","LANGUAGEID":"162","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":null,"ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"112630","DOCRECID":"18787","LANGUAGEID":"164","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":null,"ACTFROMTRANSLATION":null},{"DELLANGUAGEID":"104902","DOCRECID":"18787","LANGUAGEID":"163","DOCPARTNMBR":null,"NEWLANGUAGE":0,"CONCENTRAIDLANG":null,"ACTFROMTRANSLATION":null}]
Any idea what may be going wrong? The grid shows correct number of records and also pages in the pager. Any help will be most appreciated.
By the way, I tried GET vs POST, json vs jsonstring etc. and many other options including JSON Reader, but no luck.

The colModel index property is intended to be an exact reflection of the key in the JSON result. See the documentation:
index: The name passed to the server on which to sort the data (note that we could pass column numbers instead). Typically this is the name (or names) from the database – this is server-side sorting, so what you pass depends on what your server expects to receive.
Given that information it looks like your indexes in the example are incorrectly cased. Try correcting them to the proper case or use a numeric value.
Example:
colModel: [{ name: 'DelLanguageID', index: 'DELLANGUAGEID', width: 65, editable: false },...

Thank you Strake. This was painful for me, but quite educational. It works great now with just changing the ** ColModel**. Thanks again.

Related

Problem while uploading 10000 data to Devextreme datagrid in ASP.NET MVC

I am using devextreme datagrid in asp.net Mvc. Datagrid works fine when I am processing 5000 data. But when I want to process with 10000 data, it cannot load the data and the internal server gives an error.
My index.cshtml;
<div class="row">
<div class="col-lg-12">
<h1 class="page-header col-dark-green">
Barsan Portal <small>Gönderici/Alıcı</small>
</h1>
<div class="demo-container">
<div id="gridContainer" style="height:800px"></div>
</div>
</div>
</div>
My index.js :
$(function () {
var dataSource = new DevExpress.data.DataSource("/Nakliye/GetGondericiAlicilar");
console.log(dataSource);
$("#gridContainer").dxDataGrid({
dataSource: new DevExpress.data.CustomStore({
key: "kodu",
pageSize:50,
loadMode: "raw", // omit in the DataGrid, TreeList, PivotGrid, and Scheduler
load: function () {
return $.getJSON("/Nakliye/GetGondericiAlicilar")
.fail(function () { throw "Data loading error" });
}
}),
selection: {
mode: 'multiple'
},
renderAsync: true,
allowColumnReordering: true,
allowColumnResizing: true,
cellHintEnabled: false,
columnResizingMode: "nextColumn",
showBorders: true,
searchPanel: {
visible: true,
width: 240,
placeholder: "Ara..."
},
headerFilter: {
visible: true,
},
filterPanel: {
visible: true
},
filterRow: {
visible: true
},
loadPanel: {
enabled: true
},
groupPanel: {
visible: true,
placeholder: "Bir sütun başlığını o sütuna göre gruplandırmak için buraya sürükleyin"
},
pager: {
showPageSizeSelector: true,
allowedPageSizes: [10, 20, 50, 100, 200],
showNavigationButtons: true,
showInfo: true,
infoText: "Sayfa {0} / {1} ({2} öğe)"
},
columns: [{
dataField: "adi",
caption: "Adı"
}, {
dataField: "Adres",
}, {
dataField: "il",
width: 115,
caption: "İl"
}, {
caption: "Ülke",
dataField: "ulke",
}, {
caption: "Posta Kodu",
dataField: "postakodu",
width: 115,
}, {
caption: "Telefon",
dataField: "telefon",
width: 155,
}, {
caption: "Faks",
dataField: "faks",
width: 155,
}, {
caption: "İlgili",
dataField: "ilgili",
width: 195,
}]
});
});
My controller about action:
public ActionResult GetGondericiAlicilar() { return Json(_nakliyeService.GetGondericiAlicilar(), JsonRequestBehavior.AllowGet); }
GetGondericiAliciler() in My service :
public List<gnladresbankasi> GetGondericiAlicilar()
{
var result = _objectRawSql.Execute(StaticParams.Connstr, typeof(gnladresbankasi),
//sql functions
#"Select top 10000 kodu, adi, adres1 + ' ' + adres2 AS Adres, il, (select adi from gnlulke where kod = ulke) AS Ulke, postakodu, telefon, fax, ilgili
FROM gnladresbankasi ab WHERE Exists(select * from gnlFirmaGondericiAlici ga WHERE ab.kodu = ga.GondericiAliciKodu)").Cast<gnladresbankasi>().ToList();
return result;
}
As I mentioned, 5000 data works well, but when there is 10000 data, the loading icon returns and the data is not loaded.
Should a special action be taken regarding big data?
I found the following error in the browser network tab;
Server Error in '/' Application.
Error while serializing or deserializing using JSON JavaScriptSerializer. The length of the string exceeds the value set in the maxJsonLength property.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Can I set an unlimited length for maxJsonLength in web.config this solved my problem.

jqGrid not showing json data in MVC

jqGrid is not showing json data fetched from MVC controller, it also has a emptyrecords label which is also not visible in this case. Here is my jQuery code-
$(function () {
$("#JQGrid1").jqGrid({
url: "/CertificateDetails/GetCertificateDetails",
datatype: 'json',
mtype: 'Get',
colNames: ['Name', 'Issuer', 'Location', 'Private Key[Yes/No]'],
//data: dataArray,
colModel: [
{
key: false,
name: 'Name',
index: 'Name',
editable: false
},
{
key: false,
name: 'Issuer',
index: 'Issuer',
editable: false
},
{
key: false,
name: 'Location',
index: 'Location',
editable: false
},
{
key: false,
name: 'HasPrivateKey',
index: 'HasPrivateKey',
editable: false
}
],
height: '100%',
viewrecords: true,
caption: "Certificate Details",
emptyrecords: "No record to display!!"
});
});
Controller code:
CertDetails cd = new CertDetails();
public ActionResult Index()
{
return View();
}
//
// GET: /CertificateDetails/
public ActionResult GetCertificateDetails()
{
var stores = new Dictionary<StoreName, string>()
{
{StoreName.My, "Personal"},
{StoreName.Root, "Trusted roots"},
{StoreName.TrustedPublisher, "Trusted publishers"},
{StoreName.AddressBook, "Address Book"},
{StoreName.AuthRoot, "Auth Root"},
{StoreName.CertificateAuthority, "Certificate authority"},
{StoreName.Disallowed, "Disallowed"},
{StoreName.TrustedPeople, "Trusted people"}
// and so on
}.Select(s => new { store = new X509Store(s.Key, StoreLocation.LocalMachine), location = s.Value }).ToArray();
foreach (var store in stores)
store.store.Open(OpenFlags.ReadOnly); // open each store
var list = stores.SelectMany(s => s.store.Certificates.Cast<X509Certificate2>()
.Select(mCert => new CertDetails
{
HasPrivateKey = mCert.HasPrivateKey ? "Yes" : "No",
Name = mCert.FriendlyName != "" ? mCert.FriendlyName : "Unavailable",
Location = s.location,
Issuer = mCert.Issuer
})).ToList();
return Json(list,JsonRequestBehavior.AllowGet);
}
Here is the data returned from controller action method-
[{"Name":"Unavailable","HasPrivateKey":"Yes","Location":"Personal","Issuer":"CN=Dell Issuing Certificate Authority 302, OU=MS PKI, O=Dell Inc."},{"Name":"IIS Express Development Certificate","HasPrivateKey":"Yes","Location":"Personal","Issuer":"CN=localhost"}]
I'm getting the data in JSON format from the controller but neither jqGrid shows any data nor it shows empty records label. Any idea how to solve this issue?
You can try jQuery DataTable plugin instead, like below:
$(document).ready(function () {
$("#myGrid").dataTable({
"ajax": {
"url": "/CertificateDetails/GetCertificateDetails",
"dataSrc": ""
},
"columns": [{
"data": "Name"
}, {
"data": "Location"
}, {
"data": "Issuer"
}, {
"data": "HasPrivateKey"
}]
});
});
<table id="myGrid">
<thead>
<tr style="text-align:left;">
<th>Name</th>
<th>Location</th>
<th>Issuer</th>
<th>HasPrivateKey?</th>
</tr>
</thead>
</table>
Don't forget to add the references-
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>

How to display an image in the column of jqgrid

I want to display a image in the column of jqgrid for all data I get from '/Index/CaseBatchDetailList'. i have my jquery like,
$(function () {
var outerwidth = $('#TableCaseDtlsView').width();
$("#CaseBatchDetailList").jqGrid({
url: '/Index/CaseBatchDetailList',
datatype: 'json',
mtype: "GET",
colNames: ["Serial Number", "Denomination", "Note Image", "Back Image"],
colModel: [
{ name: "serialno", sortable: true, width: "120px", align: "center" },
{ name: "denomination", sortable: true, width: "120px", align: "left" },
{
name: "frontimageurl", sortable: false, width: "290px", align: "center", fixed: true,
formatter: function () {
return "<img src = /F:/MCP_Images/635101007551068098_324.jpg>";
}
},
{
name: "backimageurl", sortable: false, width: "290px", align: "center", fixed: true,
formatter: function () {
return "<img src = /F:/MCP_Images/635101007551068098_324.jpg>";
}
}
],
...
});
i just tried with the example for img src. I need to display the different images in different columns. As iam the beginner i dont know how to manipulate this.Kindly tell me how to achieve this.
As i saw your comment that you are having the image source in the list, then within your formatter you can do this:
formatter: function (cellvalue, options, rowobject) {
return "<img src='"+cellvalue+"'>";
}

JQGrid in MVC Not Loading the Grid

I have an MVC Edit View that contains Contact Information that is of course editable. In that view I want to add a section containing a JQGrid allowing the user to CRUD notes for the Contact but my grid is not loading with data nor is the method on the controller being called. Can anyone give me any insite?
View Code
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-info">
Contact Note</h3>
</div>
<div class="panel-body">
<div class="scrollableContainer" style="margin-top: -10px;">
<table id="JQGrid1"></table>
<div id="JQGrid1_pager"></div>
</div>
</div>
</div>
<script>
$("#JQGrid1").jqGrid({
url: '#Url.Action("GetNotes", "Contact")',
mtype: "GET",
datatype: "json",
page: 1,
jsonReader: { id: document.getElementById('SelectedContact_ContactID').value },
prmNames: { id: document.getElementById('SelectedContact_ContactID').value },
colNames: ["Id", "ContactId", "Note", "Date Created", "Created By"],
colModel: [
{ key: true, width: 50, name: "ID", hidden: false },
{ width: 60, name: "ContactID", hidden: false },
{ width: 460, name: "Note", hidden: false },
{ width: 160, name: "DateCreated",
formatter: "date", formatoptions: { srcformat: "m/d/Y h:i:s A", newformat: "mm-dd-yyyy" }, hidden: false },
{ width: 160, name: "CreatedBy", hidden: false },
],
height: "auto",
caption: "Notes",
rowNum: 5,
pager: "#JQGrid1_pager",
});
</script>
Controller Code
[HttpGet]
public JsonResult GetNotes(int id)
{
var gridModel = new ContactNotesJQGridModel();
var resultset = _contactNoteRepository.GetNotes(id);
return gridModel.ContactNotesGrid.DataBind(resultset.AsQueryable());
}
GridModel Class
public class ContactNotesJQGridModel
{
public JQGrid ContactNotesGrid { get; set; }
public ContactNotesJQGridModel()
{
ContactNotesGrid = new JQGrid
{
Columns = new List<JQGridColumn>()
{
new JQGridColumn {DataField = "ID", PrimaryKey = true},
new JQGridColumn {DataField = "ContactId"},
new JQGridColumn {DataField = "Note"},
new JQGridColumn {DataField = "DateCreated"},
new JQGridColumn {DataField = "CreatedBy"},
}
};
}
Then in the Edit Call for the Contact in the Contact Controller I set model.ContactNotesGrid = new ContactNotesJQGridModel GetNotes(int id) is never executed eventhough it's specified in the jquery.
You should use postData to add custom parameter to the server response:
postData: { id: 11 }
or
postData: {
id: function () {
return document.getElementById('SelectedContact_ContactID').value;
}
}
You need additionally modify the code of the server to use something like
return Json(someObjectWithReturnedData, JsonRequestBehavior.AllowGet);
I recommend you to add loadError callback to the list of jqGrid option (see the answer) and add gridview: true and autoencode: true option to jqGrid.
P.S. About the errors like "unable to get value of the property integer", "unable to get value of the property decimalSeperator". You should verify that you included locale file like i18n/grid.locale-en.js before jquery.jqGrid.min.js (see the documentation).
Try this :
Check 1:
Move your Jquery script inside the document ready event:
$( document ).ready(function() {
console.log( "ready!" );
});
Check 2:
Check weather your server request having any problem or not:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
}
Add the above code in your Global.asax and make sure there is no exception during the call. (Put Break point and check)
Check 3:
Watch your browser console log (F12). If there is any exception log please provide that.
Check 4:
Make sure if the call is success the expected json format is valid or not. In most of the cases it will be the major cause.
The above's are just my guesses / this is what i do first, if i have a prob. :)

JqGrid is displayed with columns and no json data

i am trying to bind JSON data to jqgrid. But, i am not getting any data.
here, is my code:
$(function () {
$("#list").jqGrid({
url:'<%:Url.Action("LoadData","Home")%>',
datatype: "JSON",
mtype: "GET",
colNames: ["sid","sname"],
colModel: [
{ name: "sid", width: 55,align:"center"},
{ name: "sname", width: 90,align:"center"},
],
jsonReader: {
repeatitems: false
},
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
autoencode: true,
caption: "My first grid"
});
});
I am using it in Asp.net MVC Application.
I am able to hit the controller and get the JSON data..but i was unsucessful in displaying data to grid.
I am getting proper json o/p from controller.
My Controller is:
public JsonResult LoadData()
{
var Data= new DataTable();
Data= DataModel.LoadData();
var JsonData = JsonConvert.SerializeObject(Packages, Formatting.Indented);
return Json(new
{
JsonData
}, JsonRequestBehavior.AllowGet);
}
I think there is error in my JQgrid jquery code. Firtly, i want to implement the jqgrid with minimal configuration.
The JSON response i am getting is:
[
{
"sid": 2,
"sname": "ABC"
},
{
"sid": 3,
"sname": "XYZ"
},
{
"sid": 4,
"sname": "CBA"
},
{
"sid": 5,
"sname": "IIT"
},
{
"sid": 6,
"sname": "NIT"
}
]
This is my HTML Structure:
<table id="list">
</table>
<div id="pager"></div>
I removed the duplicates from the data i am fetching..
The JSON result, i have checked in Text Visualizer of Visual Studio.Its fine..
Please help..
I suppose that the reason of your problem is the usage of JsonConvert.SerializeObject. You should return object instead of string. Try to use
return Json(Packages, JsonRequestBehavior.AllowGet);
directly.
Not sure you have js code in .js file on in .aspx file.
Anyway try this and check the request/response with Firefox/Chrome console
$(function () {
$("#list").jqGrid({
url:/Home/LoadData/,
datatype: "json",
mtype: "GET",
colNames: ["sid","sname"],
colModel: [
{ name: "sid", width: 55,align:"center"},
{ name: "sname", width: 90,align:"center"},
],
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
caption: "My first grid"
});
});
HTML
<table id="list"></table>
<div id="pager"></div>

Categories