JqGrid is displayed with columns and no json data - c#

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>

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+"'>";
}

How to create Kendo UI bullet chart in asp.net web application using web methods?

I have an asp.net application in which I am using multiple kendo charts. My requirement is to show the remote data using aspx web methods. But I am not getting any data in kendo charts.
Here is my code,
var dataSource = new kendo.data.DataSource({
type: "json",
transport: {
read: {
type: "POST",
url: "Commercial.aspx/FetchCounts",
contentType: 'application/json; charset=utf-8',
datatype: "json"
}, //read
parameterMap: function (options) {
return $.parseJSON(options);
}
},
serverFiltering: false,
serverSorting: false,
schema: {
data: "d",
model: {
fields: {
current: { type: "string" },
target: { type: "string" }
}
}
}
});
function createSparklines() {
$("#chart-CurrentWeekCount").kendoChart({
legend: {
visible: false
},
dataSource : dataSource,
series: [{
type: "bullet",
currentField: "current",
targetField: "target",
target: {
color: "#e13c02"
},
}],
categoryAxis: {
majorGridLines: {
visible: false
},
majorTicks: {
visible: false
}
},
valueAxis: [{
plotBands: [{
from: 0, to: 8000, color: "#ccc", opacity: .3
}],
majorGridLines: {
visible: false
},
min: 0,
max: 8000,
majorUnit: 2000,
minorTicks: {
visible: true
}
}],
tooltip: {
visible: false,
template: "Goal: #= value.target # <br /> Current: #= value.current #"
}
});
}
$(document).ready(createSparklines);
$(document).bind("kendo:skinChange", createSparklines);
The method "FetchCounts" returns the following data :
[{"current":5000,"target":7500}]
Please let me know what I am missing. Any ideas will be appreciated.
Thanks.

How to do server side Sorting/Paging in jqgrid in ASP.net MVC

I am constructing a jqgrid with the following code:
$(document).ready(function () {
$("#Data").jqGrid({
url: '/Home/LoadData',
loadonce:true,
datatype: "json",
mtype: "GET",
colNames:["ID"],
colModel: [
{ name: "Id",index:'ID',width:800, align: "center"}
],
pager: "#Pager",
rowNum: '10',
rowList: [10, 20, 30],
sortname: "ID",
sortorder: "asc",
height: "auto",
gridview:true,
sortname: "ID",
viewrecords: true,
caption: "My First Grid",
loadComplete: function (data) {
var $this = $(this),
datatype = $this.getGridParam('datatype');
if (datatype === "xml" || datatype === "json") {
setTimeout(function () {
$this.trigger("reloadGrid");
}, 100);
}
}
});
});
This is working absolutely fine. But, this is all happening in the client side. I am also using loadonce:true to the grid which means the grid loads all the data at once.
But, i am having approx 30,000 records.
loadonce=true
This is not an correct option. So, i need to implement server side sorting and server side paging.
I need to load records like page by page but sorting/Filtering should happen taking into consideration all the records.
Please help in this..if possible please provide code sample for C# code and Jquery script for paging and sorting..

Categories