I am working on a MVC application. I have written a jqGrid in my aspx page.
$(document).ready(function () {
jQuery("#jqgajax").jqGrid({
url: 'http://localhost:54136/home/fetchData',
datatype: "json",
colNames: ['ProcessName', 'WorkingSet64'],
colModel: [
{ name: 'ProcessName', index: 'ProcessName', width: 55 },
{ name: 'WorkingSet64', index: 'WorkingSet64', width: 90 }
],
rowNum: 80,
mtype:'Get',
width: 700,
rowList: [10, 20, 30],
sortname:'id',
viewrecords: true,
sortorder: "desc",
caption: "New API Example"
});
});
C# Code at controller:
var jsonData = new
{
total =10,
page = 10,
records = 10,
rows = (
from p in pu
select new
{
id = ++counter,
cell = new
{
ProcessName = p.ProcessName.ToString(),
WorkingSet64 = p.Memory.ToString()
}
}).ToArray()
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
The issue it rows are getting generated in the grid, but there is no data in the rows.
Please let me know what am I doing wrong.
Default jsonReader wait for cell as array of strings. So you should replace the part of the code
cell = new
{
ProcessName = p.ProcessName.ToString(),
WorkingSet64 = p.Memory.ToString()
}
to
cell = new [] { p.ProcessName, p.Memory.ToString() }
Related
When using jqGrid inbuilt functionality of column searching, the dropdwonlist refuses to display special characters such as ç, Ë etc. For some reason they get split into two rows. This means if we take a word "Dfëstuç" the dropdownlist or rather option list will be generated as such:
Dfë
undefined
stuç
undefined
My code is as follows:
#model WS.ViewModels.CaseViewModel
#{
ViewBag.Title = "";
Layout = "~/Views/Shared/_Layout.cshtml";
<meta charset="utf-8">
string idVendbanimiSelectValues = ":";
foreach (var item in Model.NomenklaturaVendbanimiDropDownListData.OrderBy(n => n.IdVendbanimi))
{
idVendbanimiSelectValues += ";" + item.IdVendbanimi + ":" + item.EnPershkrimi;
}
}
#section AdditionalCss {
#Styles.Render("~/Content/Styles/ui.jqgrid.min.css")
}
#section AdditionalJavaScript {
#Scripts.Render("~/bundles/jqgrid")
#Scripts.Render("~/Scripts/jqgrid-listsearch.js")
#Scripts.Render("~/Scripts/jquery.searchFilter.min.js")
<script type="text/javascript">
$(function () {
var idVendbanimiSelectValues = "#idVendbanimiSelectValues";
$('#list-grid').jqGrid({
url: '/Lenda/GridDataWithFilters/',
datatype: 'json',
mtype: 'GET',
colNames: ['CaseId','IdVendbanimi'],
colModel: [
{ name: 'CaseId', index: 'CaseId', align: 'right' },
{ name: 'IdVendbanimi', index: 'IdVendbanimi', align: 'left', stype: 'select', edittype: 'select', editoptions: { value: idVendbanimiSelectValues }, autoencode: false }
],
pager: $('#list-pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'CaseId',
sortorder: "asc",
viewrecords: true,
height: '100%',
width: '1200',
ignoreCase: true,
autoencode: true,
}).jqGrid('navGrid', '#list-pager', { edit: false, add: false, del: false, search: false, refresh: false });
$('#list-grid').jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, beforeSearch: function () {
// verify entered data before searching
var postData = $('#list-grid').jqGrid('getGridParam', 'postData');
var searchData = $.parseJSON(postData.filters);
var isThereValidationErrors = false;
var validationErrors = "";
for (var iRule = 0; iRule < searchData.rules.length; iRule++) {
var enteredValue = searchData.rules[iRule].data;
if (searchData.rules[iRule].field == "CaseId" && !isNumeric(enteredValue)) {
validationErrors += " Id Lenda must be a valid number.";
isThereValidationErrors = true;
}
}
if(isThereValidationErrors)
alert($.trim(validationErrors));
return isThereValidationErrors;
}
});
});
</script>
}
<h2>#ViewBag.Title</h2>
<br /><br />
<table id="list-grid"></table>
<div id="list-pager"></div>
Is your JSON data correctly UTF-8 encoded? e.g.:
the ë character should be encoded with two bytes, 0xC3 0xAB.
the JSON data maybe needs a UTF-8 preamble, 0xEF 0xBB 0xBF.
I have a requirement where I need to Display parent grid.
Based on the item selected in the parent, fetch data and display in child grid. I am currently doing a UI mockup and don't have the models all built yet. So the models you see below are just samples.
I can display the parent grid with data I need. I also have code to select a row in the parent grid and send the row data to the controller using ajax post. I need to use this data to populate the child grid. This is the step where I am not sure what I am doing wrong.
My controllers and views are below : Can you please help ?
--Controller:
public ActionResult GetData()
{
List<Hierarchy> lh = new List<Hierarchy>();
Hierarchy m = new Hierarchy();
m.Hierarchy1 = 1;
m.Hierarchy2 = 2;
m.Hierarchy3 = 3;
lh.Add(m);
Hierarchy n = new Hierarchy();
n.Hierarchy1 = 11;
n.Hierarchy2 = 22;
n.Hierarchy3 = 33;
lh.Add(n);
Hierarchy o = new Hierarchy();
o.Hierarchy1 = 111;
o.Hierarchy2 = 222;
o.Hierarchy3 = 333;
lh.Add(o);
return Json(new { rows = lh }, JsonRequestBehavior.AllowGet);
}
public ActionResult EditDescription(Hierarchy info)
{
List<Product> plist = new List<Product>();
if (info.Hierarchy1 == 1 && info.Hierarchy2 == 2 && info.Hierarchy3 == 3)
{
Product p = new Product();
p.ProductId = 1;
p.Productdesc = "ABC";
plist.Add(p);
Product q = new Product();
q.ProductId = 2;
q.Productdesc = "DEF";
plist.Add(q);
}
if (info.Hierarchy1 == 11 && info.Hierarchy2 == 22 && info.Hierarchy3 == 33)
{
Product p = new Product();
p.ProductId = 11;
p.Productdesc = "ABCD";
plist.Add(p);
Product q = new Product();
q.ProductId = 22;
q.Productdesc = "DDEF";
plist.Add(q);
}
return Json(new { rows = plist }, JsonRequestBehavior.AllowGet);
//return Json("Response from Edit");
}
View :
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table id="jqGrid"></table>
<div id="jqGridpager"></div>
<table id="jqSubGrid"></table>
<link href="~/Content/Theme/jquery-ui.min.css" rel="stylesheet" />
<link href="~/Content/ui.jqgrid.css" rel="stylesheet" />
#section scripts{
<script src="~/Scripts/jqGrid/grid.locale-en.js"></script>
<script src="~/Scripts/jqGrid/jquery.jqGrid.js"></script>
<script>
$(function () {
$grid = $("#jqGrid").jqGrid({
url: '#Url.Action("GetData","TEST")',
mtype: 'GET',
datatype: 'json',
colModel: [
{ label: 'Hierarchy1', name: 'Hierarchy1' },
{ label: 'Hierarchy2', name: 'Hierarchy2' },
{ label: 'Hierarchy3', name: 'Hierarchy3' },
],
loadonce: true,
pager: '#jqGridPager',
rowNum: 10,
rowList: [10, 20, 30, 50],
viewrecords: true,
height: 250,
});
$("#jqGrid").jqGrid('navGrid', '#jqGridPager', { edit: false, add: false, del: false })
$("#jqGrid").jqGrid('setGridParam', {
onSelectRow: function (rowid, iRow, iCol, e) {
var rowData = $("#jqGrid").jqGrid("getRowData", rowid);
//alert(rowData.Key);
var data0 = { Hierarchy1: rowData.Hierarchy1, Hierarchy2: rowData.Hierarchy2, Hierarchy3: rowData.Hierarchy3 };
// var data0 = { numberId: "1", companyId: "531" };
// var roles = ["role1", "role2", "role3"];
jQuery.ajax({
type: "POST",
url: "#Url.Action("EditDescription")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data0),
success: function (data) {
//alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
$grid1 = $("#jqSubGrid").jqGrid({
url: '#Url.Action("EditDescription", "TEST")',
mtype: 'GET',
datatype: 'json',
colModel: [
{ label: 'ProductId', name: 'ProductId' },
{ label: 'Productdesc', name: 'Productdesc' },
],
loadonce: true,
pager: '#jqGridPager',
rowNum: 10,
rowList: [10, 20, 30, 50],
viewrecords: true,
height: 250,
});
}
});
});
</script>
}
Hi tried to load the jqgrid with json by passing javascript object. but the grid is not loading.
Below is my javascript code
oSearchParam = {
InvoiceNo: document.getElementById('txtInvoiceNumber').value,
}
var grid = $("#dataGrid")[0];
//my code
$("#dataGrid").jqGrid({
// setup custom parameter names to pass to server
prmNames: {
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
// postData: { oSearchParam: oSearchParam },
// setup ajax call to webmethod
datatype: function (postdata) {
$(".loading").show(); // make sure we can see loader text
$.ajax({
url: 'InvoiceSearch.aspx/GetSearchResultData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function (data, st) {
if (st == "success") {
var grid = $("#dataGrid")[0];
alert(data.d);
grid.addJSONData(JSON.parse(data.d));
}
},
error: function () {
alert("Error with AJAX callback");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id", //index of the column with the PK in it
repeatitems: true
},
autowidth: true,
shrinkToFit: true,
height: 'auto',
colNames: ['InvoiceNo'],
colModel: [
{ name: 'InvoiceNo', index: 'InvoiceNo', width: 55, search: false }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery("#pagingGrid"),
sortname: "InvoiceNo",
sortorder: "asc",
viewrecords: true,
caption: "Grid Title Here",
gridComplete: function () {
$(".loading").hide();
}
}).jqGrid('navGrid', '#pagingGrid', { edit: true, add: true, del: true },
{}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true }, //search
{}
)
And below is the webmethod
[WebMethod]
public static string GetSearchResultData(int? numRows, int? page, string sortField, string sortOrder, SearchParam oSearchParam)
{
DataTable dtInvoiceList = Mymethod();
var query = dtInvoiceList.AsEnumerable()
.Select(i => new SearchParam
{
InvoiceNo = i.Field<string>("InvoiceNo"),
// ImageId = i.Field<string>("DocID"),
InvoiceAmount = i.Field<decimal>("Amount"),
// ImageId = i.Field<string>("DocID"),
Status = i.Field<string>("Status"),
CurrentlyWith = i.Field<string>("CurrentlyWith")
}).ToList();
//--- setup calculations
int pageIndex = page ?? 1; //--- current page
int pageSize = numRows ?? 10; //--- number of rows to show per page
int totalRecords = query.Count(); //--- number of total items from query
int totalPages = (int)Math.Ceiling((decimal)totalRecords / (decimal)pageSize); //--- number of pages
var sortedRecords = query
.Skip((pageIndex - 1) * pageSize) //--- page the data
.Take(pageSize).ToList();
//--- format json
var jsonData = new
{
totalpages = totalPages, //--- number of pages
page = pageIndex, //--- current page
totalrecords = totalRecords, //--- total items
rows = (
from row1 in sortedRecords
select new
{
i = row1.ImageId,
cell = new string[] {
row1.InvoiceNo,
row1.Status,
row1.CurrentlyWith,
row1.InvoiceAmount.ToString(),
}
}
).ToArray()
};
string result = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);
return result;
}
My webmethod is not getting called.
Can anybody help me on this.
i am populating jquery flexigrid by returning records in json format from c# controller. however i am facing little bit problem. I am adding herf column to delete the particular record. it works fine but i cant find way to confirm it before deleting it. below is my c# code which returns records to flexigrid.
C# Controller Snippet
private JsonResult CreateFlexiJson(IEnumerable<user> items, int page, int total)
{
var CurentsessionUser = Session["sessionUserId"].ToString();
List<Object> rows = new List<Object>();
foreach (var item in items)
{
rows.Add(new
{
id = item.id,
cell = new string[] {
item.msisdn,
item.pin,
item.subtype,
CurentsessionUser =="csagent"?"":String.Format("Change Pin"),
CurentsessionUser =="csagent"?"":String.Format("Delete")
}
});
}
var result = new { page = page, total = total, rows = rows };
return Json(result);
}
public ActionResult Delete(string subno)
{
try
{
wmas_subsEntities entitymodel = new wmas_subsEntities();
var customer = from p in entitymodel.users where p.msisdn == subno select p;
if (customer.ToList().Count > 0)
{
entitymodel.users.Remove(customer.First());
entitymodel.SaveChanges();
}
//return Json("Successfully deleted the user registeration");
return View("Index");
}
catch (Exception ex)
{
throw ex;
}
}
View
$('#CustomerList').flexigrid({
dataType: 'json',
colModel: [
{
display: 'Subscriber No.',
name: 'msisdn',
width: 100,
sortable: true,
align: 'left'
},
{
display: 'Pin Code',
name: 'pin',
width: 100,
sortable: true,
align: 'left'
},
{
display: 'Postpaid/Prepaid',
name: 'subtype',
width: 100,
sortable: true,
align: 'left'
},
{
display: '',
name: '',
width: 100,
sortable: true,
align: 'left'
},
{
display: '',
name: '',
width: 100,
sortable: true,
align: 'left'
}
],
title: 'Customer',
useRp: true,
rp: 15,
width: 600,
height:400,
singleSelect: true
});
In CreateFlexiJson action, change below line
CurentsessionUser =="csagent"?"":String.Format("Delete")
TO
CurentsessionUser =="csagent"?"":String.Format("<a href='javascript:void(0)' onclick='deleteSubscriber(\"" + item.msisdn + "\")'>Delete</a>")
And add javascript function deleteSubscriber
function deleteSubscriber(subno) {
if (confirm("Are you sure to delete Subscriber (No. = " + subno + ")")) {
location.href = "Delete?subno=" + subno;
}
}
Ok. I have several JQuery Ajax posts, which are calling individual WebMethods. I've come across an issue, and i now need to combine the webmethods into one, but then still be able to split out the return values according to the list. So for example, I need something that returns multiple lists, so that my Ajax call, can then render the respective Jquery Datatables like: table 1 = drList[0], table 2 =drList[1] etc.
Webmethod code is below:
[WebMethod]
[ScriptMethod]
public static List<GlobalClasses.ValueDateSummary> GetValueDateSummary()
{
string TSQL = "SELECT * FROM vw_view1 WHERE (SenderBIC ='" + HttpContext.Current.User.Identity.Name + "') ORDER BY ValueDate DESC";
DataTable dtValueDateSummary = null;
GlobalClasses.ValueDateSummary objSummary;
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MIReporting"].ConnectionString);
using (conn)
{
conn.Open();
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(TSQL, conn))
{
dtValueDateSummary = new DataTable();
sqlAdapter.Fill(dtValueDateSummary);
}
}
List<GlobalClasses.ValueDateSummary> drList = new List<GlobalClasses.ValueDateSummary>();
foreach (DataRow row in dtValueDateSummary.Rows)
{
objSummary = new GlobalClasses.ValueDateSummary();
objSummary.fld1= row["1"].ToString();
objSummary.fld2 = row["2"].ToString();
objSummary.fld3 = row["3"].ToString();
objSummary.fld5 = row["4"].ToString();
drList.Add(objSummary);
}
return drList;
}
the only difference between this and the other webmethod call is the view being used.
the Ajax call is :
$.ajax({
type: 'POST',
url: 'Default.aspx/GetValueDateSummary',
data: '{}',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
renderMsgSummary(response.d);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
})
the renderMsgSummary is the Jquery datatable, so this need to be as follows:
renderMsgSummary(response.d[0]);
renderOtherTable(response.d[1]);
OK - almost there, trying to merge the client side script in now.
<script type="text/javascript">
$(document).ready(function () {
function renderMsgVal(result) {
var dtMsgValData = [];
$.each(result, function () {
dtMsgValData.push([
this.SenderBIC,
this.ValueDate,
this.MessageType,
this.Reference
]);
});
function renderMsgSummary(result) {
var dtMsgSumData = [];
$.each(result, function () {
dtMsgSumData.push([
this.SenderBIC,
this.MessageDate,
this.MessageType,
this.Count
]);
});
$('#tblValueDateSummary').dataTable({
"aaData": dtMsgValData,
"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100]]
'asStripClasses': null,
"iDisplayLength": 10,
//"aaSorting": [[0, "asc"]],
"bJQueryUI": true,
"bFilter": true,
"bAutoWidth": false,
"bProcessing": true,
// "sDom": 'RC<"clear">lfrtip',
"sDom": 'RC<"H"lfr>t<"F"ip>',
//Scrolling .......
"sScrollY": "250px",
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true,
//Dynamic Language .......
"oLanguage": {
//"sZeroRecords": "There are no messages that match your,
"sLengthMenu": "Display _MENU_ records per,
"sInfo": "Displaying _START_ to _END_ of _TOTAL_ records",
"sInfoEmpty": "Displaying _START_ to _END_ of _TOTAL_m
"sInfoFiltered": "(filtered from _MAX_ total records)",
"sEmptyTable": 'No Rows to display.....!',
"sSearch": "Search all columns:",
"sLoadingRecords": "Please wait - loading..."
},
"oSearch": {
"sSearch": "",
"bRegex": false,
"bSmart": true
}
});
$('#tblMessageDateSummary').dataTable({
"aaData": dtMsgSumData,
"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100]]
"asStripClasses": null,
"iDisplayLength": 10,
"aaSorting": [[0, "asc"]],
"bJQueryUI": true,
"bFilter": true,
"bAutoWidth": true,
"bProcessing": true,
"sDom": 'RC<"clear">lfrtip',
//"sDom": '<"F"ip>l',
//Scrolling .......
"sScrollY": "250px",
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true,
//Dynamic Language .......
"oLanguage": {
// "sZeroRecords": "There are no messages that match your,
"sLengthMenu": "Display _MENU_ records per,
"sInfo": "Displaying _START_ to _END_ of _TOTAL_ records",
"sInfoEmpty": "Showing 0 to 0 of 0 records",
"sInfoFiltered": "(filtered from _MAX_ total records)",
"sEmptyTable": 'No Rows to display.....!',
"sSearch": "Search all columns:"
},
"oSearch": {
"sSearch": "",
"bRegex": false,
"bSmart": true
}
});
}
$.ajax({
type: 'POST',
url: 'Default.aspx/GetMessageDetails',
data: '{}',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
//console.log(response);
//alert(response.d);
renderMsgVal(response.d[0]);
renderMsgSummary(response.d[1]);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
});
</script>
not sure if this is possible?
If I understand correctly, you can return a List of Lists.
public static List<List<GlobalClasses.ValueDateSummary>> GetValueDateSummary()
{
var allLists = new List<List<GlobalClasses.ValueDateSummary>>();
foreach (DataRow row in dtValueDateSummary.Rows)
{
objSummary = new GlobalClasses.ValueDateSummary();
objSummary.fld1= row["1"].ToString();
objSummary.fld2 = row["2"].ToString();
objSummary.fld3 = row["3"].ToString();
objSummary.fld5 = row["4"].ToString();
drList.Add(objSummary);
}
allLists.Add(drList);
//add other lists to allLists
//..
return allLists;
}
wrap your various lists into a bigger class i.e.
make a class something like
public class Wrapper
{
public List<GlobalClasses.ValueDateSummary> list1 {get;set;}
public List<GlobalClasses.ValueDateSummary> list2 {get;set;}
public List<SomeOtherClassCollectino> list3{get;set;}
}
and return this wrapper in your webmethod i.e.
[WebMethod]
[ScriptMethod]
public static List<GlobalClasses.ValueDateSummary> GetValueDateSummary()
{
// your db logic
Wrapper wrapper = new Wrapper();
List<GlobalClasses.ValueDateSummary> drList = new List<GlobalClasses.ValueDateSummary>();
foreach (DataRow row in dtValueDateSummary.Rows)
{
objSummary = new GlobalClasses.ValueDateSummary();
objSummary.fld1= row["1"].ToString();
objSummary.fld2 = row["2"].ToString();
objSummary.fld3 = row["3"].ToString();
objSummary.fld5 = row["4"].ToString();
drList.Add(objSummary);
}
wrapper.list1 = drList;
//similarly fetch other lists
//wrapper.list2 = drList2;
return new JavaScriptSerializer().Serialize(wrapper);
}
and on the client side you can access it like:
var jsonData = $.parseJSON(msg.d);
renderMsgSummary(jsonData.list1);
renderMsgSummary(jsonData.list2);