Jqfrid Subgrid Data not loading - javascript

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>

Related

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

Navgrid not displaying add/delete on JQGrid

Please find my code attached :
Jqgrid creation:
<script type="text/javascript">
$(function () {
$("#datagrid").jqGrid({
url: 'jqgridwithwebmethod.aspx/ConvertDataTabletoString',
datatype: 'json',
mtype: 'POST',
serializeGridData: function (postData) {
// return JSON.stringify(postData);
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
colNames: ['Name', 'Age', 'Mobile', 'City', 'Sex', 'FirstName', 'LatName', 'Address', 'Landline'],
colModel: [
{ name: 'Name', index: 'Name', width: 200, frozen: true, editable: true },
{ name: 'Age', index: 'Age', sorttype: 'int', width: 200, editable: true },
{ name: 'Mobile', index: 'Mobile', sorttype: 'int', width: 200, editable: true },
{ name: 'City', index: 'City', width: 200, editable: true },
{ name: 'Sex', index: 'Sex', width: 200, editable: true },
{ name: 'FirstName', index: 'FirstName', width: 200, editable: true },
{ name: 'LastName', index: 'LastName', width: 200, editable: true },
{ name: 'Address', index: 'Address', width: 200, editable: true },
{ name: 'Landline', index: 'Landline', width: 300, editable: true }
],
pager: '#nav',
rowNum: 10,
sortname: 'Name',
autowidth: true,
sortorder: "desc",
shrinkToFit: false,
//forceFit:false,
loadonce: true,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
jsonReader: {
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
root: function (obj) { return obj.d; },
repeatitems: false
//id: "0"
},
caption: 'My first grid'
});
$("#datagrid").jqGrid('setFrozenColumns');
});
**$('#datagrid').jqGrid('navGrid', '#nav',**
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete"
});
</script>
The function ConvertDataTabletoString is defined as:
[WebMethod]
public static List<Dictionary<string, object>> ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select * from studen with(nolock)", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(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;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
The Jqgrid use data received from SQL server.
The edit/add/delete icons are not dispalying on the Jqgrid..
Kindly help..
You placed call of navGrid method on the wrong place. You have block $(function () {...}); which meany document ready event handler. You placed call of navGrid method out of the block. It's wrong. You should mode it one line above (directly after the call of setFrozenColumns) to fix the problem.

unable to display success message after editing the row in jqgrid

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.

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?

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

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.

Categories

Resources