jqGrid userData to show a value in View (asp.net mvc3) - javascript

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
:&nbsp <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.

Related

jqGrid inline-edit POST without editurl?

I am trying to find the information about editurl. Currently, i am working on the framework which does not permit editurl. The calls must go through javascript function which in-turn invokes the component on serverside.
Question is it possible to POST the data to javascript function instead of editurl?
I am experimenting with following:
$(document).ready(function () {
console.log(">>>1");
//--
action.setCallback(this, function(a) {
if (a.getState() === "SUCCESS") {
result = a.getReturnValue();
console.log(result);
//---=
var editActionOptions = {
keys: true,
url:null,
oneditfunc: function (rowid) {
console.log("row with rowid=" + rowid + " is editing.");
},
aftersavefunc: function (rowid, response, options) {
console.log("row with rowid=" + rowid + " is successfuly modified.");
}
};
//-------------------------------------------------------------------------------------------------------
$("#jqGrid").jqGrid({
editurl: 'clientArray',
datatype: "local",
data:result,
colModel: [
{
label: "Edit Actions",
name: "actions",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{
labe: 'ID',
name: 'empid',
width: 75
},
{
label : 'Name',
name: 'Name',
width: 140,
editable: true // must set editable to true if you want to make the field editable
},
{
label: 'dob',
name: 'dob',
width: 100,
editable: true
},
{
label: 'dln',
name: 'dln',
width: 120,
editable: true
}
],
sortname: 'empid',
loadonce: true,
onSelectRow: editRow,
onSave:onSaveRow,
editParams: editActionOptions,
width: 780,
height: 400,
rowNum: 150,
pager: "#jqGridPager"
});
//------------------------------------------------------------------------------------------------------
} else if (a.getState() === "ERROR") {
$A.log("Errors", a.getError());
}
});
$A.enqueueAction(action);
var lastSelection;
function editRow(id) {
console.log(id);
if (id && id !== lastSelection) {
var grid = $("#jqGrid");
grid.jqGrid('restoreRow',lastSelection);
grid.jqGrid('editRow',id, {keys: true} );
lastSelection = id;
}
};
function onSaveRow(id){
console.log(id);
}

Jqfrid Subgrid Data not loading

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>

Not able to fetch querystring value in MVC4 Action result

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!!

Why my jqgrid is not showing any data?

I want to use a complete jqgrid but it is not working. It is not showing any data but controller action returning the values. Here is my controller action code which is used in my project. My purpose is to use pager in jqgrid. Please help me and i need some solutions & tips for using jqgrid in mvc.
public ActionResult itemList(jqGridViewModel jqGridParameters)
{
var item = from t in db.tbl_Item select t;
var count = item.Count();
int pageIndex = jqGridParameters.page;
int pageSize = jqGridParameters.rows;
int startRow = (pageIndex * pageSize) + 1;
int totalRecords = count;
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var result = new
{
total = totalPages,
page = pageIndex,
records = count,
rows = item.Select(x => new
{
x.id,
x.itemcode,
x.name,
x.qtyLimit,
x.Quantity,
x.sellingPrice,
x.supplier,
x.unitType,
x.vat,
x.batchno,
x.brand,
x.buyingPrice,
x.catg
}
).ToArray()
.ToPagedList(pageIndex, pageSize)
.Select(x => new
{
id = x.id,
cell = new string[] { x.id.ToString(),
x.name,
x.itemcode,
Convert.ToString(x.qtyLimit),
x.Quantity.ToString(),
x.sellingPrice.ToString(),
x.supplier,
x.unitType,
x.vat.ToString(),
x.batchno,
x.brand,
x.buyingPrice.ToString(),
x.catg
}
}
).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
And my view code
jQuery("#list").jqGrid({
cache: false,
async: false,
url: '/Settings/itemList/',
datatype: 'json',
mtype: 'GET',
colNames: ['New Item', 'Batch No', 'Supplier', 'Unit', 'B. Price', 'S. Price','Item Code','Vat','Limit'],
colModel: [
{ name: 'name', index: 'name', width: 110, align: 'center' },
{ name: 'batchno', index: 'batchno', width: 110, align: 'center' },
{ name: 'supplier', index: 'supplier', width: 110, align: 'center' },
{ name: 'unitType', index: 'unitType', width: 110, align: 'center', editoptions: { readonly: 'readonly' } },
{ name: 'buyingPrice', index: 'buyingPrice', width: 110, align: 'center', editoptions: { readonly: 'readonly' } },
{ name: 'sellingPrice', index: 'sellingPrice', align: 'center' },
{ name: 'itemcode', index: 'itemcode', width: 110, align: 'center'},
{ name: 'vat', index: 'vat', width: 110, align: 'center', editoptions: { readonly: 'readonly' } },
{ name: 'qtyLimit', index: 'qtyLimit', align: 'center' }
],
pager: jQuery('#pager'),
rowNum: 15,
rowList: [5, 10, 20, 50],
sortname: 'iid',
sortorder: "desc",
viewrecords: true,
width: 960,
height: 200,
loadOnce: true,
imgpath: '/scripts/themes/coffee/images',
caption: 'Stock Information',
jsonReader: {
root: "Data",
page: "CurrentPage",
total: "TotalPages",
records: "TotalRecords",
repeatitems: false,
id: "0"
},
recordtext: "Products {0} - {1} of {2}",
rownumbers: true,
pagerpos: 'center'
});
You define JsonReader like this:
jsonReader: {
root: "Data",
page: "CurrentPage",
total: "TotalPages",
records: "TotalRecords",
repeatitems: false,
id: "0"
},
And ther on controller side you passing data to anonimous object that have this properties:
var result = new
{
total = totalPages,
page = pageIndex,
records = count,
...
}
Your property names should be the same as you define in your JsonReader

How to display a collection of results to a grid cell using jqGrid

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?

Categories

Resources