JQGrid in MVC Not Loading the Grid - c#

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. :)

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>

JSON data is not displaying in JQGrid

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.

Razor asp.net: access javascript variable

Currently I have this:
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: {
transport: {
read: {
url: "#Html.Raw(
Url.Action(
"Filter_Rooms",
"Room",
new {
pFilter = false,
pCapacity = 25,
pBeamer = true,
pTelevision = false
}))",
dataType: "json"
},
}
}
}
]
These parameters pFilter = false, pCapacity = 25, pBeamer = true, pTelevision = false, for the filter are now hard coded but actually I want them from:
HTML
<div class="checkbox">
<label>
<input id="chkBeamer" type="checkbox"> Beamer available
</label>
</div>
Filter rooms
Javascript
$(document).ready(function () {
$("#btnFilter").click(function () {
var pFilter = document.getElementById("chkBeamer").checked;
});
});
Can I get the javascript to use the pFilter parameter instead of the hard-coded ones?
HTMLHidden
<div class="checkbox">
<label>
#Html.Hidden("pBeamer", true);
<input id="chkBeamer" type="checkbox"> Beamer available
</label>
</div>
Javascript Resources
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: {
transport: {
read: {
url: "#Html.Raw(
Url.Action(
"Filter_Rooms",
"Room",
new {
pBeamer = ("#pBeamer")???
}))",
dataType: "json"
},
}
}
}
]
There are two ways in which you can do this:-
1) You can have hidden fields for each of these four fields which you can fill in your Javascript function on click of btnFilter. Access those hidden fields while using resources.
#Html.Hidden("pFilter","<value>");
You can access these hidden fields in your code below.
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: {
transport: {
read: {
url: "#Html.Raw(
Url.Action(
"Filter_Rooms",
"Room",
new {
pFilter = <get value from hidden field>,
pCapacity = <get value from hidden field>,
pBeamer = <get value from hidden field>,
pTelevision = <get value from hidden field>
}))",
dataType: "json"
},
}
}
}
]
2) You can have global variables to which you assign values on btnFilter click and use it in resources as you are doing currently.
I would suggest you to follow the first solution.

Kendo Grid Not showing Data

I am trying to bind Data from database to KendoUI Grid but Data is not Showed up... I am getting data from database successfully converting into serialized code but data does not showed up in Kendo Grid.. plz help me...
<div id="example" class="k-content">
<div id="grid"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#grid").kendoGrid({
dataSource:
{
type:"odata",
serverPaging: true,
serverSorting:true,
pageSize:100,
transport:
{
read:
{
url:"Fetchdata.aspx",
contentType: "application/json;charset=utf-8",
dataType: "odata",
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false
}
}
}
},
height:100,
scrollable:
{
virtual: true
},
sortable: true,
columns: [
"dptId",
{ title: "Name", field: "dptName" },
{ title: "Description", field: "dptdescription" }
]
});
});
</script>
</div>
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(GetData());
Response.End();
}
protected string GetData()
{
EmployeeBM empbm = new EmployeeBM();
List < Departement> list= new List<Departement>();
list = empbm.BindDepartment();
return GridData(1, 1,list.Count, list);
}
public string GridData(int noOfPages, int startPage, int noOfRecords, List<Departement> list)
{
var gridData = new
{
total = noOfPages,
page = startPage,
records = noOfRecords,
rows = list,
};
var jsonSerializer = new JavaScriptSerializer();
return jsonSerializer.Serialize(gridData);
}
I see quite a few issues in your code:
The dataType cannot be set to "odata". Try "json". To quote the jQuery documentation:
Default: Intelligent Guess (xml, json, script, or html)
The Kendo DataSource type is also set to "odata" but your page is clearly not an OData service. Remove that.
You are setting jsonReader which is not supported by the Kendo DataSource. I guess you need to use the schema setting.

Categories