I am facing trouble passing values from JS to MVC actionresult.
Below is my JS code in which I want to populate JqGrid. During debugging the values of both the parameters are coming as null. I checked the requestURL in the console it is generating correctly bu the values are passed as null.
HTML Partial View
<form>
<table>
<tr>
<td>
<input type="text" id="exchangePlanId" title="Exchange Plan Id", placeholder = "Exchange Plan Id" />
</td>
<td>
<input type="text" id="planYear" title="Plan Year" , placeholder="Plan Year" />
</td>
<td>
<input type="submit" id="getFilteredData" onclick="getFilteredProductData()"value="Filter" class="appButton" />
</td>
</tr>
</table>
</form>
front End JS code:
function getFilteredProductData() {
var exchangePlanId = document.getElementById('exchangePlanId').value;
var planYear = document.getElementById('planYear').value;
var requestURL = '/RxProductData/FilterRxProductData/?' + "exchangePlanId=" + exchangePlanId + "&planYear=" + planYear;
console.log(requestURL);
$(function () {
$('#listGrid').jqGrid({
url: requestURL,
datatype: 'json',
mtype: 'Get',
colName: ['Id', 'ExchangePlanID', 'OracleFinanceMarketNbr', 'IssueStateCode', 'PlanID', 'PrimaryPlatformCode', 'PlanYear', 'VersionRefID'],
colModel: [
{ key: true, hidden: true, name: 'Id', index: 'Id' },
{ key: false, name: 'ExchangePlanID', index: 'ExchangePlanID' },
{ key: false, name: 'OracleFinanceMarketNbr', index: 'OracleFinanceMarketNbr' },
{ key: false, name: 'IssueStateCode', index: 'IssueStateCode' },
{ key: false, name: 'PlanID', index: 'PlanID' },
{ key: false, name: 'PrimaryPlatformCode', index: 'PrimaryPlatformCode' },
{ key: false, name: 'PlanYear', index: 'PlanYear' },
{ key: false, name: 'VersionRefID', index: 'VersionRefID' }],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
width: 'auto',
viewrecords: true,
caption: 'Rx Calc Product Data',
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
autowidth: true,
multiselect: false
})
});
}
Here is the code on Back end.
[HttpPost]
public JsonResult FilterRxProductData(string exchangePlanId, string planYear,int rows, int page = 1, string transactionGUID = DefaultTransactionId)
{
Guid transactionGuid = base.CalculateGuid(transactionGUID);
var rxProductDataList = crossRefBll.GetAllRxProductData(transactionGuid);
if (rxProductDataList != null && rxProductDataList.Count > 0)
{
if (exchangePlanId != null && planYear == null)
{
}
else if (exchangePlanId == null && planYear != null)
{
}
else
{
}
int totalRecords = rxProductDataList.Count;
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = rxProductDataList
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
else
{
throw new Exception("No Rx Product Data was Returned : GetAllRxProductData");
}
}
I have used HttpPost attribute over my jsonresult that's why I was not able to get the querystring value.
So silly of me. :/
Correct attribute to use is [HttpGet]
Yay!!
Related
I have a C# WebMethod that gets some data from my SQL database and then turns it into a JSON string.
Here is the WebMethod
[WebMethod]
public object getCustomers() {
string constr = ConfigurationManager.ConnectionStrings["Indigo2.Properties.Settings.Constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT custid, cust_name FROM [dbo].[customers] WHERE archive = 'No'"))
{
cmd.Connection = con;
List<Customers> customers = new List<Customers>();
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new Customers
{
custid = sdr["custid"].ToString(),
cust_name = sdr["cust_name"].ToString(),
});
}
con.Close();
String result = JsonConvert.SerializeObject(customers);
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(result);
return result;
}
}
}
}
I am them trying to pass this data on the client side, using JavaScript.
Here is my JS
function buildSelect(response) {
alert(JSON.stringify(response));
var $tulem = $("<select><option value=''>All</option></select>");
$.each(JSON.parse(response).rows, function (i, item) {
$("<option></option>", { value: item.custid })
.text(item.custid)
.appendTo($tulem);
});
return $tulem;
}
The JSON.Parse fails with following errors
XML Parsing Error: syntax error
Location: https://localhost:44338/WebService1.asmx/getCustomers
Line Number 1, Column 1: getCustomers:1:1
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 722 of the JSON data
If I return my JSON the console it looks like this.
"[{\"custid\":\"ACC001\",\"cust_name\":\"Accenda Limited\"},{\"custid\":\"ANI001\",\"cust_name\":\"Animal Friends\"},{\"custid\":\"APP001\",\"cust_name\":\"Appello\"},{\"custid\":\"ATL001\",\"cust_name\":\"Atlas Contract Furniture\"},{\"custid\":\"BNS001\",\"cust_name\":\"BNS Ltd\"},{\"custid\":\"HAR001\",\"cust_name\":\"Harrow Health\"},{\"custid\":\"IND001\",\"cust_name\":\"Indigo Integrated Solutions\"},{\"custid\":\"MER001\",\"cust_name\":\"Merton Health Limited\"},{\"custid\":\"POL001\",\"cust_name\":\"Polyhose (UK) Ltd\"},{\"custid\":\"PUR001\",\"cust_name\":\"Purbeck School\"},{\"custid\":\"QUE001\",\"cust_name\":\"Queen Elizabeth's School\"},{\"custid\":\"SER001\",\"cust_name\":\"Serbus Limited\"},{\"custid\":\"STS001\",\"cust_name\":\"STS Defence\"},{\"custid\":\"WIM001\",\"cust_name\":\"Wimborne Academy Trust\"}]<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<anyType xmlns:q1=\"http://www.w3.org/2001/XMLSchema\" d1p1:type=\"q1:string\" xmlns:d1p1=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://tempuri.org/\">[{\"custid\":\"ACC001\",\"cust_name\":\"Accenda Limited\"},{\"custid\":\"ANI001\",\"cust_name\":\"Animal Friends\"},{\"custid\":\"APP001\",\"cust_name\":\"Appello\"},{\"custid\":\"ATL001\",\"cust_name\":\"Atlas Contract Furniture\"},{\"custid\":\"BNS001\",\"cust_name\":\"BNS Ltd\"},{\"custid\":\"HAR001\",\"cust_name\":\"Harrow Health\"},{\"custid\":\"IND001\",\"cust_name\":\"Indigo Integrated Solutions\"},{\"custid\":\"MER001\",\"cust_name\":\"Merton Health Limited\"},{\"custid\":\"POL001\",\"cust_name\":\"Polyhose (UK) Ltd\"},{\"custid\":\"PUR001\",\"cust_name\":\"Purbeck School\"},{\"custid\":\"QUE001\",\"cust_name\":\"Queen Elizabeth's School\"},{\"custid\":\"SER001\",\"cust_name\":\"Serbus Limited\"},{\"custid\":\"STS001\",\"cust_name\":\"STS Defence\"},{\"custid\":\"WIM001\",\"cust_name\":\"Wimborne Academy Trust\"}]</anyType>"
What am I doing wrong, what can I do to change this into a standard clean JSON string?
UPDATED
This is where the WebMethod is called from, its the dataURL, for a field called cust_name, defined in the editoptions of a JQGRID.
jQuery("#jqquotes").jqGrid({
url: '../We
bService1.asmx/getDataQuotes',
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) {
return typeof obj.d.rows === "string" ? $.parseJSON(obj.d.rows) : obj.d.rows;
},
page: function (obj) { return obj.d.page; },
total: function (obj) { return obj.d.total; },
records: function (obj) { return obj.d.records; },
repeatitems: false
},
loadComplete: function () {
$('#jqquoteitems').trigger('reloadGrid');
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
onSelectRow: function () {
showDetailsGrid();
},
height: 'auto',
//autowidth: true,
rowNum: 5,
rowList: [5, 10, 15],
colNames: ['Doc ID', 'Quote #', 'Summary', 'Date', 'Customer', 'Contact', 'custid'],
colModel: [
{ name: 'docid', key: true, index: 'docid', width: 55, editable: true },
{ name: 'quote_number', index: 'quote_number', width: 45, editable: true },
{ name: 'summary', index: 'summary', width: 160, editable: true, edittype: 'textarea' },
{
name: 'quote_date', formatter: 'date', datefmt: "d-m-Y", editoptions: { dataInit: initDateEdit },
formatoptions: { srcformat: "d/m/Y H:i:s", newformat: "d-m-Y" }, index: 'quote_date', width: 60, editable: true
},
{
name: 'cust_name', index: 'cust_name', width: 140, align: "left", editable: true, edittype: "select",
editoptions: {
dataUrl: '/WebService1.asmx/getCustomers',
buildSelect: buildSelect
}
},
...
It's crashing because the end of your JSON string you have "<anyType>" which is not a parseable for JSON.
The main grid loads fine but When I click on the plus icon the subgrid data does not load, its says loading.... But nothing happens. Don't know what I'm missing. Please help.
Below is the code I'm using:
Controller
namespace SubGrid.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Index");
}
RoopaDBEntities db = new RoopaDBEntities();
public JsonResult GetDepts(string sidx, string sord, int page, int rows, string filter)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var DeptsResults = db.Table_Dept.Select(
a => new
{
a.DeptID,
a.DeptName,
a.HOD,
a.Status,
});
int totalRecords = DeptsResults.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "Desc")
{
DeptsResults = DeptsResults.OrderByDescending(s => s.DeptID);
DeptsResults = DeptsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
DeptsResults = DeptsResults.OrderBy(s => s.DeptID);
DeptsResults = DeptsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = DeptsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public JsonResult GetEmps(string sidx, string sord, int page, int rows, string filter)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var EmpsResults = db.Table_Emp.Select(
a => new
{
a.DeptID,
a.EmpID,
a.EmpName,
a.Gender,
a.Salary,
});
int totalRecords = EmpsResults.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "Desc")
{
EmpsResults = EmpsResults.OrderByDescending(s => s.EmpID);
EmpsResults = EmpsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
EmpsResults = EmpsResults.OrderBy(s => s.EmpID);
EmpsResults = EmpsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
records = totalRecords,
rows = EmpsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
}
JavaScript
$(function () {
$("#ListGrid").jqGrid({
url: "../Home/GetDepts/",
datatype: 'json',
mtype: 'Get',
colNames: ['DeptID', 'DeptName', 'HOD', 'Status'],
colModel: [
{ key: true, name: 'DeptID', index: 'DeptID' },
{ key: false, name: 'DeptName', index: 'DeptName' },
{ key: false, name: 'HOD', index: 'HOD' },
{ key: false, name: 'Status', index: 'Status' }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30, 40],
height: 225,
sortname: 'DeptID',
sortorder: "desc",
viewrecords: true,
loadonce: true,
ignoreCase: true,
caption: "Department List",
autowidth: true,
multiselect: false,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
id: "0",
},
subGrid: true,
subGridOptions: {
"plusicon": "ui-icon-triangle-1-e",
"minusicon": "ui-icon-triangle-1-s",
"openicon": "ui-icon-arrowreturn-1-e",
},
subGridRowExpanded: function (subgrid_Id, rowid) {
var $subgrid = $("<table id='" + subgrid_Id + "_t'></table>");
$("#" + subgrid_Id)
.append($subgrid);
$subgrid.jqGrid({
url: '../Home/GetEmps/' + '?id=' + rowid,
postData: {
q: 2,
id: rowid,
DeptID: rowid
},
datatype: "json",
mtype: 'Get',
colNames: ['Dept ID', 'Emp ID', 'Emp Name', 'Gender','Salary'],
colModel: [
{ index: 'DeptID', name: 'DeptID' },
{ index: 'EmpID', name: 'EmpID', key: true },
{ index: 'EmpName', name: 'EmpName'},
{ index: 'Gender', name: 'Gender' },
{ index: 'Salary', name: 'Salary' }
],
viewrecords: true,
height: '100%',
autowidth: true,
rowNum: 5,
idPrefix: rowid + "_",
})
},
loadComplete: function () {
$("tr.jqgrow:odd").css("background", "LightBlue");
}
})
.navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true })
});
Index:
#model SubGrid.Models.Dept
#{
ViewBag.Title = "Index";
}
<div>
<table>
<tr>
<td width="100%"><tableid="ListGrid"></table></td>
<td><div id="pager"></div></td>
</tr>
</table>
</div>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/Dept.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/grid.subgrid.js"></script>
<script src="~/Scripts/jquery.jqGrid.js"></script>
I'm developing a web based application using bootstrap.
I'm trying to implement inline editing in my grid on page load but i'm facing some issue while displaying the success or failure message after performing edit function.
Here is my code :
$(document).ready(function () {
var GetUrl = Web_Path + '/Test/TestHandler/GetTestData/' + AjaxHandlerName;
jQuery("#jqGrid-container").jqGrid({
url: GetUrl,
datatype: 'json',
mtype: 'POST',
postData: { SearchInfo: function () { return getSearchPostData() } },
colNames: [' ', 'ID', 'Name', 'ContactNo', 'EmpId', 'MailId', 'RoleName'],
colModel: [
{ name: 'myac', index: '', width: 80, fixed: true, sortable: false, resize: false,
formatter: 'actions',
formatoptions: {
keys: true,
delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback }
}
},
{ name: 'Id', index: 'Id', hidden: true, editable: true },
{ name: 'Name', index: 'Name', validation: { required: true }, sortable: true, editable: true, editoptions: { size: "40", maxlength: "50"} },
{ name: 'ContactNo', index: 'ContactNo', sortable: false, editable: true, editoptions: { size: "20", maxlength: "30"} },
{ name: 'EmpId', index: 'EmpId', sortable: false, editable: true, editoptions: { size: "20", maxlength: "30"} },
{ name: 'MailId', index: 'MailId', sortable: false, editable: true, editoptions: { size: "40", maxlength: "50"} },
{name: 'RoleName', index: 'RoleName', sortable: false }
],
editurl: ISM_Web_Path + '/Test/TestHandler/UpdateTestContacts/' + ISMAjaxHandlerName,
ajaxRowOptions: {
afterEditRow: function (rowid, cellname, value, iRow, iCol) {
alert('success');
}
},
serializeRowData: function (postdata) {
return { ContactInfo: JSON.stringify(postdata) };
},
jsonReader: {
id: 'Id',
repeatitems: false
},
height: "100%",
pager: '#jqGrid-pager',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'Id',
sortorder: 'desc',
viewrecords: true,
caption: "JQ grid data",
loadComplete: function () {
var table = this;
updatePagerIcons(table);
}
});
});
function getSearchPostData() {
var searchData = {};
searchData.Id=1;
return JSON.stringify(searchData);
}
function updatePagerIcons(table) {
var replacement =
{
'ui-icon-seek-first': 'icon-double-angle-left bigger-140',
'ui-icon-seek-prev': 'icon-angle-left bigger-140',
'ui-icon-seek-next': 'icon-angle-right bigger-140',
'ui-icon-seek-end': 'icon-double-angle-right bigger-140'
};
$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
})
}
<div class="row">
<div class="col-xs-12">
<table id="jqGrid-container" class="ui-jqgrid ui-widget ui-widget-content ui-corner-all">
</table>
<div id="jqGrid-pager">
</div>
</div>
</div>
Handler function
public void UpdateTestContacts(HttpContext context)
{
TestContact contactInfo =new TestContact();
string jsonData = context.Request.Params["ContactInfo"];
MemoryStream TestContactMs = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TestContact));
contactInfo = (RelationshipContact)serializer.ReadObject(TestContactMs );
//call manger function
// return true or false
}
TestContact.cs
public class TestContact
{
public int Id { get; set; }
public string Name { get; set; }
public string ContactNo { get; set; }
public string EmpId { get; set; }
public int RelId { get; set; }
public int TypeId { get; set; }
public string MailId { get; set; }
public string RoleName { get; set; }
}
I have used jquery.jqGrid.min.js.
I'm unable to display success message after editing the row successfully.
I have used afterEditRow
Please help me out.
There are no afterEditRow callback function inside of ajaxRowOptions. I recommend you to use aftersavefunc callback function of inline editing which can be specified as afterSave function of formatoptions:
formatter: 'actions',
formatoptions: {
keys: true,
afterSave: function (rowid, response, postdata, options) {
alert("success");
},
delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback }
}
ajaxRowOptions: {
success: function (data, textStatus) {
if(textStatus=="true")
{
alert('success');
}
else
{
alert('failure');
}
}
}
I'm returning true in handler.
Above code is working for me.
I have a database containing many to many relations, so a Post can have multiple Tags, and a Tag can be assigned to multiple Posts
I am using jqgrid to display all the posts in a grid using the following code:
Javascript:
//grid
jQuery(document).ready(function () {
//post grid
jQuery("#tablePosts").jqGrid({
url: '/Admin/ListPosts/',
datatype: 'json',
mtype: 'GET',
colNames: ['ID', 'Title', 'Short Description', 'Description', 'Category', 'Tags', 'Published', 'Posted Date', 'Modified Date', 'UrlSlug', 'Meta'],
colModel: [
{ name: 'PostID', index: 'PostID', width: 50, stype: 'text' },
{ name: 'Title', index: 'Title', width: 150 },
{ name: 'ShortDescription', index: 'ShortDescription', width: 150, sortable: false },
{ name: 'Description', index: 'Description', width: 200, sortable: false },
{ name: 'Category', index: 'Category', width: 100 },
{ name: 'Tags', index: 'Tags', width: 100, sortable: false},
{ name: 'Published', index: 'Published', width: 80 },
{ name: 'PostedOn', index: 'PostedOn', width: 130 },
{ name: 'Modified', index: 'Modified', width: 130 },
{ name: 'UrlSlug', index: 'UrlSlug', width: 80, sortable: false },
{ name: 'Meta', index: 'Meta', width: 80, sortable: false }
],
rowNum: 10,
rowList: [5, 10, 20, 50],
viewrecords: true,
pager: '#pagerPosts',
height: '100%',
sortname: 'PostedOn',
sortorder: "desc",
//width to null && shrink to false so the width of the grid inherit parent and resizes with the parent
width: null,
shrinkToFit: false
});
});
and this is my controller action:
public ActionResult ListPosts(string sidx, string sord, int page, int rows)
{
int pageNo = page - 1;
int pageSize = rows;
//for paging
int totalRecords = repository.TotalPosts(true) + repository.TotalPosts(false);
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows); //round up to smallest integral number greater than returned valued
//for records
var posts = repository.AllPosts(pageNo, pageSize, sidx, sord == "asc");
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (
from post in posts
select new
{
id = post.PostID,
cell = new string[] {
post.PostID.ToString(),
post.Title,
post.ShortDescription,
post.Description,
post.Category.Name,
post.Tags.ToString(),
post.Published.ToString(),
post.PostedOn.ToString(),
post.Modified.ToString(),
post.UrlSlug,
post.Meta
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
In my rows, I defined post tags as a string just to remove errors and I couldn't figure out how to display Tags as a list, and this is my grid:
as you can see, Tags column is not displaying Tag names, how do you display them correctly?
Insted of post.Tags.ToString() use string.Join(",",post.Tags.Select(t => t.Name))
Or pass array of tags to your view and use custom formatter
Formatter may looks like this:
function tagFormatter(cellvalue, options, rowObject)
{
var text = ""
if (cellvalue.length > 0)
{
for (var i = 0; i < cellvalue.length; i++)
{
text += cellvalue[i].Name;
if (i < cellvalue.length - 1)
{
text += ", ";
}
}
}
return text;
}
It will display comma-separated tags names;
And tag row:
{ name: 'Tags', index: 'Tags', width: 100, sortable: false, formatter: tagFormatter },
Is it helpful?
I'm new to jqGrid. My task is now to show TotalDiabetes in View (asp.net MVC3) which has jqGrid, so I have chosen userData. My Controller code for jqGrid as follows,
extraPersons = ExtraPersonService.GetAllExtraPersons();
int TotalDiabetesCount = extraPersons.First().TotalDiabetes;
int pageIndex = gridSettings.pageIndex;
int pageSize = gridSettings.pageSize;
int totalRecords = extraPersons.Count;
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
int startRow = (pageIndex - 1) * pageSize;
int endRow = startRow + pageSize;
var jsonData = new
{
total = totalPages,
page = pageIndex,
records = totalRecords,
userdata = new { TotalDiabetesCount = "totalDiabetes" },
rows =
(
extraPersons.Select(e => new
{
Id = e.ExtraPersonId,
Name = e.FirstName + " " + e.LastName,
Diabetes = e.Diabetes ,
BP = e.BP,
Arrived = e.Arrived,
TreatmentApplied = e.TreatmentApplied,
})
).ToArray()
};
return Json(jsonData);
My JavaScript code for jqGrid as follows,
jQuery("#allextraperson").jqGrid({
url: '/ExtraPerson/GetAllExtraPersons/',
datatype: 'json',
mtype: 'POST',
colNames: gridInfoJSON.GridModel.ColumnDisplayArray,
colModel: [
{ name: 'Id', index: 'Id', hidden: true },
{ name: 'Name', index: 'Name', width: 200, formatter: generateNameLink },
{ name: 'Diabetes', index: 'Diabetes', width: 55, align: 'center', formatter: generateDiabetesLabel },
{ name: 'BP', index: 'BP', width: 50, align: 'center', formatter: generateBPLabel },
{ name: 'Arrived', index: 'Arrived', width: 70, align: 'center', formatter: generateArrivedLabel },
{ name: 'Delete', index: 'Delete', width: 75, align: 'center', formatter: deleteformatter }
],
jsonReader: {
id: 'Id',
repeatitems: false
},
height: "100%",
width: 970,
pager: '#allextraperson-pager',
rowNum: 10,
rowList: [10, 20, 30, 50],
sortname: 'Id',
sortorder: 'asc',
viewrecords: true,
loadComplete: function (data) {
var table = this;
setTimeout(function () {
updatePagerIcons(table);
}, 0);
var totaldiabetes = jQuery("#allextraperson").getGridParam('totalDiabetes');
alert("Total diabetes:" + totaldiabetes);
}
});
}
My View Code to show TotalDiabetes as follows
<span class="user_info muted" style="position: inherit;">Total Diabetes
:  <strong class="orange"> totalDiabetes </strong></span>
The alert shows Total diabetes:null
I don't know what I did wrong, please anyone suggest me a solution.
Myself found what I did wrong, In the Controller code, I have replaced the line
userdata = new { TotalDiabetesCount = "totalDiabetes" },
with this line
userdata = new { totalDiabetes = TotalDiabetesCount }
In my javascript code, I have replaced the line
var totaldiabetes = jQuery("#allextraperson").getGridParam('totalDiabetes');
with these lines,
var userData = jQuery("#allextraperson").getGridParam('userData');
if (userData.totalDiabetes) {
$('#total-diabetes').text(userData.totalDiabetes);
}
And in my View I have added an id = "total-diabetes" to strong tag in html. Thus I got the output.