jqgrid inline editing autocomplete dropdown - jqgrid

Found answers in Oleg post but unable to solve in my case.
I have a jqGrid with inline editing. That works fine. One column 'SupervisorUserID' has a dropdown box with list of entries which retrieved from a database query already.
As the entries are too much, I want to have an input field which will autocomplete/search the dropdown list.
Please help me to achieve this. Thanks.
My code,
public JsonResult PersonnelManagementGrid(string sidx, string sord, int page, int rows)
{
objPersonnelManagementViewModel = new PersonnelManagementViewModel();
objPersonnelManagementViewModel.PersonnelManagementModelList = (List<PersonnelManagementModel>) Session["PersonnelList"];
var results = objPersonnelManagementViewModel.PersonnelManagementModelList.Select(x => new
{
x.UserID,
x.Name,
x.InActive,
x.SupervisorUserID,
});
int pageIndex = Convert.ToInt16(page) - 1;
int pageSize = rows;
int totalRecords = results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{ results = results.OrderByDescending(e => e.Name); }
else { results = results.OrderBy(e => e.Name); }
results = results.Skip(pageIndex * pageSize).Take(pageSize);
var sbLocations = new System.Text.StringBuilder();
Dictionary<string, string> personnelList = new Dictionary<string, string>();
personnelList = objPersonnelManagementViewModel.PersonnelManagementModelList.ToDictionary(x => x.UserID, x => x.Name);
//personnelList.Add("1","one");
//personnelList.Add("2", "two");
//personnelList.Add("3", "three");
foreach (var sortedLocation in personnelList)
{
sbLocations.Append(sortedLocation.Key);
sbLocations.Append(':');
sbLocations.Append(sortedLocation.Value);
sbLocations.Append(';');
}
if (sbLocations.Length > 0)
sbLocations.Length -= 1; // remove last ';'
var jsonResults = new
{
colModelOptions = new
{
SupervisorUserID = new
{
formatter = "select",
edittype = "select",
editoptions = new
{
value = sbLocations.ToString()
}
}
},
total = totalPages,
page,
records = totalRecords,
rows= results,
};
return Json(jsonResults, JsonRequestBehavior.AllowGet);
}
Jquery:
$(function () {
$("#PersonnelManagementGrid").jqGrid({
url: '/PersonnelManagement/PersonnelManagementGrid',
datatype: "json",
contentType: "application/json; charset-utf-8",
mtype: 'Get',
colNames: ['UserID', 'Name', 'Role', 'Active?', 'Supervisor', 'Change Active', 'Try Delete'],
colModel: [
{ key: true, name: 'UserID', index: 'UserID', hidden: true },
{
name: 'Name', index: 'Name', editable: false, width: "460", sortable: true,
},
{
name: 'Role', index: 'Role', editable: false, width: "200", sortable: true,
},
{
name: 'InActive', index: 'InActive', editable: false, width: "200", sortable: true,
},
{
name: 'SupervisorUserID', index: 'SupervisorUserID', editable: true, formatter: 'select', width: "200", sortable: true,
edittype: 'select', width: "200", align: "center",
},
{
name: "Change Active", sortable: false, width: "200", align: "center",
formatter: function (cellvalue, options, rowObj) {
var cBtn = '<input type="button" class="button" value="Change" onclick= "changeActive(' + "'" + rowObj.id + "','" + "values" + "','" + "values" + '\')"/>'
return cBtn;
}
},
{
name: "Try Delete", sortable: false, width: "200", align: "center",
formatter: function (cellvalue, options, rowObj) {
var cBtn = '<input type="button" value="Delete" onclick= "tryDelete(' + "'" + rowObj.id + "','" + "values" + "','" + "values" + '\')"/>'
return cBtn;
}
}
],
beforeProcessing: function (response) {
var $self = $(this),
options = response.colModelOptions, p;
if (options != null) {
for (p in options) {
if (options.hasOwnProperty(p)) {
$self.jqGrid("setColProp", p, options[p]);
}
}
}
},
pager: jQuery('#pager'),
rowNum: 15,
rowList: [5, 10, 15],
height: '100%',
width: '1328',
viewrecords: true,
caption: 'Personnel Management',
//loadonce: true,
emptyrecords: 'No records to display',
scrollerbar: false,
jsonReader: {
root: "rows",
page: "pagenumbers",
total: "totalnumbers",
records: "records",
repeatitems: false,
id: "0"
},
hidegrid: false,
multiselect: false,
onSelectRow: function (id) {
rowSelect(id);
},
}).navGrid('#pager', { edit: false, add: false, del: false, search: false, cancel: false, reload: false, refresh: false });
});

Related

page not loading on button click but works on link button in jqGrid in MVC

I have a page (Steps_Details.cshtml) with a jqgrid in MVC that i want to call it in 3 ways and it loads data based on the Unique_code i send as parameter. 1st way) i have another page (Rep_Contracts_Steps.cshtml) with a jqgrid and i have a link button in it and by clicking on this link button and sending the parameter data loads properly. 2nd way) a link on main menu with no parameters and it loads all data with no filtering.
the 3rd way and the one I've encountered problem with ) i have a button in a page and i send the parameter. it directs to the view but doesn't load the page.(in fact it doesn't call the "Get_Contracts_Steps_Details" Action in my HomeController when i use btnRep)
"Steps_Details.cshtml"
<script type="text/javascript">
$(document).ready(function () {
$('#list').jqGrid({
caption: "گزارش جزییات پیگیری قراردادها",
url: '#Url.Action("Get_Contracts_Steps_Details","Home")',
datatype: 'json',
jsonReader: {
root: "Rows",
page: "Page",
total: "Total",
records: "Records",
repeatitems: true,
userdata: "UserData",
id: "Vahed_Descript",
cell: "RowCells"
},
mtype: 'GET',
//columns names
colNames: [' ردیف ',
' کد تایید ',
' عنوان تایید ',
' کاربر تایید کننده ',
' تاریخ تایید ',
' توضیحات',
' کاربر ثبت کننده',
' تاریخ ثبت',
' کاربر ویرایش کننده' ,
' تاریخ ویرایش' ,
' عنوان واحد ',
' کد دبیرخانه ',
' شماره درخواست ',
' شرح درخواست ',
' تاریخ ثبت درخواست',
' مبلغ برآوردی ',
''
],
//columns model
colModel: [
{ name: 'MCS_ID', index: 'MCS_ID', align: 'Right', width: "60px", editable: true, editoptions: { readonly: "readonly" } },
{ name: 'MCS_ConfirmId', index: 'MCS_ConfirmId', align: 'Right', width: "60px", editable: false },
{ name: 'MWL_Descript', index: 'MWL_Descript', align: 'Right', editable: false },
{ name: 'MCS_ConfirmUser', index: 'MCS_ConfirmUser', align: 'Right', editable: true, edittype: 'text' },
{ name: 'MCS_ConfirmDate', index: 'MCS_ConfirmDate', align: 'Right', width: "80px", editable: true, edittype: 'text',
editrules: { required: true }
},
{ name: 'MCS_Note', index: 'MCS_Note', align: 'Right', width: "300px", editable: true, edittype: 'text' },
{ name: 'MCS_CreatorUserName', index: 'MCS_CreatorUser', align: 'Right', editable: false },
{ name: 'MCS_Creation_Date', index: 'MCS_Creation_Date', align: 'Right', width: "80px", editable: false },
{ name: 'MCS_EditorUserName', index: 'MCS_EditorUserName', align: 'Right', editable: false },
{ name: 'MCS_EditDate', index: 'MCS_EditDate', align: 'Right', width: "80px", editable: false },
{ name: 'DESCRIPT', index: 'DESCRIPT', align: 'right', editable: false },
{ name: 'DABIR_VAHED_CODE', index: 'DABIR_VAHED_CODE', align: 'right', width: "60px", editable: false },
{ name: 'CONTRACT_REQ_ID', index: 'CONTRACT_REQ_ID', align: 'right', width: "100px", editable: false },
{ name: 'CONTRACT_REQ_SUBJECT', index: 'CONTRACT_REQ_SUBJECT', align: 'right', editable: false },
{ name: 'D_CONTRACT_REQ', index: 'D_CONTRACT_REQ', align: 'right', width: "100px", editable: false },
{ name: 'AMNT_TOT_ESTIMATE', index: 'AMNT_TOT_ESTIMATE', align: 'right', width: "100px", editable: false,
formatter: 'currency', formatoptions:
{ decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 0 }
},
{ name: 'MCS_REQ_UNIQUE', index: 'MCS_REQ_UNIQUE', width: 1, align: 'left', hidden: true },
],
pager: $('#pager'),
rowNum: 200,
rowList: [10, 20, 40, 60, 80, 100, 150, 200, 300],
sortname: 'CONTRACT_REQ_SUBJECT',
sortorder: 'asc',
viewrecords: true,
altRows: true,
shrinkToFit: false,
width: 'auto',
height: '300px',
hidegrid: false,
direction: "rtl",
gridview: true,
rownumbers: true,
footerrow: true,
userDataOnFooter: true,
scrollerbar: true,
loadComplete: function () {
$("tr.jqgrow:odd").css("background", "#E0E0E0");
},
loadError: function (xhr, st, err) {
jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
}
, loadonce: true
})
.jqGrid('navGrid', "#pager",
//enabling buttons
{ add: false, del: true, edit: true, search: true, refresh: true },
//edit option
{
url: '#Url.Action("EditSteps_Details", "Home")' ,
width: 'auto',
checkOnUpdate: true,
checkOnSubmit: true,
closeOnEscape: true,
closeAfterEdit: true,
beforeShowForm: function (form) {
centerDialog(form, $('#list'));
},
afterSubmit: function (response, postdata) {
$("#list").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
return [true, "", ''];
},
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
//delete options
{
url: '#Url.Action("DeleteSteps_Details", "Home")', reloadAfterSubmit: false
, beforeShowForm: function (form) {
centerDialog(form, $('#list'));
},
});
function centerDialog(form, grid) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
}
function toolbarSearching() {
$("#list").jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
};
$("#list").jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
var maxNameLength = 10;
$("input[id=gs_name]").blur(function () {
var $th = $(this).closest(".ui-search-toolbar>th"),
colIndex = $th[0].cellIndex,
$colHeader = $th.parent().siblings(".ui-jqgrid-labels").children("th").eq(colIndex),
colHeaderText = $colHeader.children("div").text();
if (this.value.length > maxNameLength) {
alert(colHeaderText + ' is longer than ' + maxNameLength + ' characters.');
}
});
$('#gs_invdate').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true
});
})
</script>
"Steps_Details" Action
[HttpGet]
public ActionResult Steps_Details(string REQ_UNIQE)
{
if (Session["LoginName"] == null)
{
return RedirectToAction("Index", "Home");
}
else
{
if (REQ_UNIQE != null)
{
if (REQ_UNIQE != "")
{
Session["REQ_UNIQE"] = REQ_UNIQE.ToString();
}
}
return View();
}
}
"button and the dropdownlist that i send the value of it as a parameter"
<div class="form-group">
#Html.DropDownListFor(model => model.Req_Unique, (SelectList)ViewBag.Contract_Req_Sub_List, "انتخاب", new { #class = "form-control", #id = "ddlContrReqSub", #onchange = "javascript:GetWork_Level(this.value);" })
<input type="button" name="submit" value="گزارش" id="btnRep" class="w3-button w3-MyDarkBlue w3-padding-large w3-margin-bottom" />
</div>
"javascript code for btnRep"
$(document).ready(function () {
$("#btnRep").click(function () {
var REQ_UNIQE = $("#ddlContrReqSub").val();
$.ajax({
url: "/Home/Steps_Details",
type: "GET",
data: { REQ_UNIQE: REQ_UNIQE },
});
});
});
"Get_Contracts_Steps_Details Action in HomeController"
[HttpGet]
public ActionResult Get_Contracts_Steps_Details(JqGridRequest request )
{
using (rw_mis_dbEntities dc = new rw_mis_dbEntities())
{
if (Session["REQ_UNIQE"] != null )
{
var list = dc.MVC_REP_Contracts_Steps_Details_By_Req_Unique(Security.SharedMembers.shrd_Year_Abbr, Security.SharedMembers.shrd_Vahed_Id, Security.SharedMembers.shrd_User_Id, "", "", 0, new Guid(Session["REQ_UNIQE"].ToString())).ToList();
var pageIndex = request.page - 1;
var pageSize = request.rows;
var totalRecords = list.Count;
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
var contractsQuery = list.AsQueryable();
contractsQuery = new JqGridSearch().ApplyFilter(contractsQuery, request._search, request.searchField, request.searchString,
request.searchOper, request.filters, this.Request.Form);
if (string.IsNullOrWhiteSpace(request.oper))
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize)
.Take(pageSize);
}
else if (request.oper == "excel")
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize);
}
var contractsList = contractsQuery
.OrderBy(request.sidx + " " + request.sord)
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
var jqGridData = new JqGridData
{
UserData = new // نمايش در فوتر
{
Name = "جمع صفحه"
},
Total = totalPages,
Page = request.page,
Records = totalRecords,
Rows = (contractsList.Select(Contract => new JqGridRowData
{
Id = Convert.ToInt32(Contract.MCS_ID),
RowCells = new List<string>
{ Contract.MCS_ID.ToString(),
Contract.MCS_ConfirmId.ToString(),
Contract.MWL_Descript,
Contract.MCS_ConfirmUser,
Contract.MCS_ConfirmDate.ToString() ,
Contract.MCS_Note ,
Contract.MCS_CreatorUserName.ToString() ,
Contract.MCS_CreationDate.ToString() ,
Contract.MCS_EditorUserName.ToString() ,
Contract.MCS_EditDate .ToString() ,
Contract.VAHED_DESCRIPT ,
Contract.DABIR_VAHED_CODE,
Contract.CONTRACT_REQ_ID ,
Contract.CONTRACT_REQ_SUBJECT ,
Contract.D_CONTRACT_REQ ,
Contract.AMNT_TOT_ESTIMATE.ToString() ,
Contract.MCS_REQ_UNIQUE.ToString ()
}
})).ToList()
};
Session["REQ_UNIQE"] = null;
return Json(jqGridData, JsonRequestBehavior.AllowGet);
}
else
{
var list = dc.MVC_REP_Contracts_Steps_Details(Security.SharedMembers.shrd_Year_Abbr, Security.SharedMembers.shrd_Vahed_Id, Security.SharedMembers.shrd_User_Id, "", "", 0 ).ToList();
var pageIndex = request.page - 1;
var pageSize = request.rows;
var totalRecords = list.Count;
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
var contractsQuery = list.AsQueryable();
contractsQuery = new JqGridSearch().ApplyFilter(contractsQuery, request._search, request.searchField, request.searchString,
request.searchOper, request.filters, this.Request.Form);
if (string.IsNullOrWhiteSpace(request.oper))
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize)
.Take(pageSize);
}
else if (request.oper == "excel")
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize);
}
var contractsList = contractsQuery
.OrderBy(request.sidx + " " + request.sord)
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
var jqGridData = new JqGridData
{
UserData = new // نمايش در فوتر
{
Name = "جمع صفحه"
},
Total = totalPages,
Page = request.page,
Records = totalRecords,
Rows = (contractsList.Select(Contract => new JqGridRowData
{
Id = Convert.ToInt32(Contract.MCS_ID),
RowCells = new List<string>
{ Contract.MCS_ID.ToString(),
Contract.MCS_ConfirmId.ToString(),
Contract.MWL_Descript,
Contract.MCS_ConfirmUser,
Contract.MCS_ConfirmDate.ToString() ,
Contract.MCS_Note ,
Contract.MCS_CreatorUserName.ToString() ,
Contract.MCS_CreationDate.ToString() ,
Contract.MCS_EditorUserName.ToString() ,
Contract.MCS_EditDate .ToString() ,
Contract.VAHED_DESCRIPT ,
Contract.DABIR_VAHED_CODE,
Contract.CONTRACT_REQ_ID ,
Contract.CONTRACT_REQ_SUBJECT ,
Contract.D_CONTRACT_REQ ,
Contract.AMNT_TOT_ESTIMATE.ToString() ,
Contract.MCS_REQ_UNIQUE.ToString ()
}
})).ToList()
};
return Json(jqGridData, JsonRequestBehavior.AllowGet);
}
}
}
Thanks in advance
I just changed
<input type="button" name="submit" value="گزارش" id="btnRep" class="w3-button w3-MyDarkBlue w3-padding-large w3-margin-bottom" />
To
<input type="button" name="submit" value="گزارش" id="btnRep" class="w3-button w3-MyDarkBlue w3-padding-large w3-margin-bottom" onclick="location.href='#Url.Action("Steps_Details", "Home")?Req_Unique=' + $('#ddlcontrreqsub').val()" />
and it worked
Method Get_Contracts_Steps_Details is with return type ActionResult. But jqGrid defined with datatype:'json'.
If Get_Contracts_Steps_Details is going to return json result for jqGrid, use return type string or JsonResult.

On First load of jqgrid how to load page of specific record?

Using Jquery.Jqgrid v4.4.4
I have 10 pages in my State grid, i want to display the page which holds state name 'Tamilnadu' on first of the jqgrid loads. Not to bring the state on the first page, need to display that page on the first time.
EDIT: My Jqgrid code, here i have 'State' column contains 10+ pages , in one of the page 'Tamilnadu' state record is there. Please help me on how to load the grid with that page on first load.
// Setting up County Grid properties
$(function () {
$("#CountyGrid").jqGrid({
url: '/ControlTables/GetCountyResult',
datatype: "json",
contentType: "application/json; charset-utf-8",
mtype: 'Get',
colNames: ['CountyIdentifier', 'Active', 'State', 'County', 'County Number', AddNewBtn],
colModel: [
{
Key: true, name: 'CountyIdentifier', index: 'CountyIdentifier', width: 16, editable: false, sortable: true, align: "left", classes: "grid-col",
hidden: true, displayName: "CountyIdentifier"
},
{
name: 'ActiveFlag', index: 'ActiveFlag', width: 4, align: 'center', editable: true,
edittype: 'checkbox', editoptions: { value: "True:False", defaultValue: "True" }, formatter: "checkbox", displayName: "Active"
},
{
name: 'StateIdentifier', index: 'StateIdentifier', editable: true, formatter: 'select', sortable: true,
edittype: 'select', width: 19, align: "left", classes: "grid-col", editoptions: { style: "height:23px;" }, displayName: "State", valueField: "StateText",
},
{
name: 'CountyText', index: 'CountyText', width: 19, editable: true, sortable: true, align: "left", classes: "grid-col",
editoptions: { style: "height:23px;", maxlength: "48", dataInit: function (el) { $(el).css('text-transform', 'uppercase'); } }, displayName: "County"
},
{
name: 'CountyNumber', index: 'CountyNumber', width: 7, editable: true, sortable: true, align: "left", classes: "grid-col",
editoptions: { style: "height:23px;", maxlength: "5" }, displayName: "County Number"
},
{
name: "action", index: "action", sortable: false, editable: false, align: "center", width: "7", displayName: "Action"
},
],
// Call select row function
onSelectRow: function (id) {
if (onPagingLastSel) {
$('#CountyGrid').jqGrid('resetSelection', lastsel, true);
onPagingLastSel = false;
}
rowSelect(id);
},
onPaging: function () {
//Prompt to save pending changes when the user try to navigate Next/Previous/Front/Last page.
if (lastsel != null) {
$('#CountyGrid').jqGrid('saveRow', lastsel, {});
var editrowData = jQuery("#CountyGrid").getRowData(lastsel);
var editRow_ActiveFlag = editrowData['ActiveFlag']
var editRow_StateIdentifier = editrowData['StateIdentifier']
var editRow_CountyText = editrowData['CountyText']
var editRow_CountyNumber = editrowData['CountyNumber']
$('#CountyGrid').jqGrid('editRow', lastsel, {});
if ((lastsel_StateIdentifier != editRow_StateIdentifier && editRow_StateIdentifier != undefined)||
(lastsel_CountyText != editRow_CountyText && editRow_CountyText != undefined) ||
(lastsel_CountyNumber != editRow_CountyNumber && editRow_CountyNumber != undefined) ||
(lastsel_ActiveFlag != editRow_ActiveFlag && editRow_ActiveFlag != undefined)) {
DialogConfirmSave("GENL-002");
onPagingLastSel = true;
return 'stop';
}
else {
lastsel = null;
//enable New Button
$("#NewBtnId").removeClass('add-new-button-disable');
$("#NewBtnId").removeAttr("disabled");
}
}
},
// load all States into jqGrid dropdown
beforeProcessing: function (response) {
var $self = $(this),
options = response.colModelOptions, StateIdentifier;
if (options != null) {
for (StateIdentifier in options) {
if (options.hasOwnProperty(StateIdentifier)) {
$("#CountyGrid").jqGrid("setColProp", StateIdentifier, options[StateIdentifier]);
}
}
}
},
// Grid column header alignment to the left diable new button for general users
loadComplete: function () {
$("#CountyGrid").jqGrid("setLabel", "Active", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "StateIdentifier", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "CountyText", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "CountyNumber", "", { "text-align": "left" })
},
pager: jQuery('#CountyPager'),
rowNum: jqGridRowCount,
rowList: GridRowList,
viewrecords: true,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
multiselect: false,
autowidth: true,
height: 560,
hidegrid: false,
}).navGrid('#CountyPager', {
edit: false, add: false, del: false, search: false, refresh: false, reload: false, restoreAfterSelect: false
})
});
My Controller code:
public JsonResult GetCountyResult(string sidx, string sord, int page, int rows, bool getAllRecords = false)
{
objCountyViewModel = new CountyViewModel();
int totalRecords = 0;
if (Session["CountyList"] != null && Session["CountyList"] is List<CountyModel>)
{
objCountyViewModel.CountyModelList = (List<CountyModel>)Session["CountyList"];
if (objCountyViewModel.CountyModelList != null)
{
Session["CountyList"] = objCountyViewModel.SortCounty(sidx, sord);
totalRecords = objCountyViewModel.CountyModelList.Count();
}
}
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
rows = getAllRecords ? totalRecords : rows;
var jsonData = new
{
colModelOptions = new
{
StateIdentifier = new
{
formatter = "select",
edittype = "select",
editoptions = new
{
value = objCountyViewModel.GetStateDropdownList()
}
}
},
total = totalPages,
page,
records = totalRecords,
rows = objCountyViewModel.GetCountyPageList(page, rows)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}

Sorting issue with jqgrid

I want to implement sorting of visible rows in jqgrid the default behavior of jqgrid is sorting all records. i have handled it on server side but the problem is when i do sort i always get page as 1 even when i am on page2 or other.below is my code i also tried loadComplete, & onPaging method.
$(document).ready(function () {
$("#grid").jqGrid({
emptyrecords: "No records to view",
ignoreCase: true,
datatype: "json",
url: '#Url.Action("LoadData", "Home")',
mtype: "GET",
height: 'auto',
rowNum: 5,
rowList: [5, 10, 15, 20],
colNames: ['EmployeeId', 'EmployeeCity', 'EmployeeName'],
colModel: [
{ name: 'EmployeeId', index: 'EmployeeId', key: true, width: 200, sorttype: 'int' },
{ name: 'EmployeeName', index: 'EmployeeName', width: 200, sorttype: 'text' },
{ name: 'EmployeeCity', index: 'EmployeeCity', width: 200, sorttype: 'text' }
],
pager: '#pager',
sortname: 'EmployeeId',
viewrecords: true,
sortorder: "asc",
caption: "jqGrid Example"
}).navGrid("#pager",
{ search: false, refresh: false, add: false, edit: false, del: false },
{},
{},
{}
);
});
And , My server side code is ,
public ActionResult LoadData(int page, int rows, string sidx, string sord)
{
List<Employee> employeeList = new List<Employee>();
for (int i = 1; i < 18; i++)
{
employeeList.Add(
new Employee() { EmployeeId = i, EmployeeCity = "Mumbai_" + i, EmployeeName = "Jason_" + i }
);
}
var totalRecords = 0;
var totalPages = 0;
var griddata = new List<Employee>();
if (employeeList != null)
{
griddata = employeeList.Skip((page - 1) * rows).Take(rows).ToList();
switch (sidx.ToLower())
{
case "employeeid":
if (sord.ToLower() == "asc")
griddata.OrderBy(x => x.EmployeeId).ToList();
else
griddata.OrderByDescending(x => x.EmployeeId).ToList();
break;
default:
griddata.OrderByDescending(x => x.EmployeeName).ToList();
break;
}
totalRecords = employeeList.Count;
totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);
}
var employeeListData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = griddata,
};
return Json(employeeListData, JsonRequestBehavior.AllowGet);
}
You are ordering your data on server side after you get paging. I mean this section:
griddata = employeeList.Skip((page - 1) * rows).Take(rows).ToList();
switch (sidx.ToLower())
{
case "employeeid":
if (sord.ToLower() == "asc")
griddata.OrderBy(x => x.EmployeeId).ToList();
else
griddata.OrderByDescending(x => x.EmployeeId).ToList();
break;
default:
griddata.OrderByDescending(x => x.EmployeeName).ToList();
break;
}
Just change the order like this:
switch (sidx.ToLower())
{
case "employeeid":
if (sord.ToLower() == "asc")
employeeList = employeeList.OrderBy(x => x.EmployeeId).ToList();
else
employeeList = employeeList.OrderByDescending(x => x.EmployeeId).ToList();
break;
default:
employeeList = employeeList.OrderByDescending(x => x.EmployeeName).ToList();
break;
}
griddata = employeeList.Skip((page - 1) * rows).Take(rows).ToList();
Yes finally done in a simple way.
Added one hidden field.
<input type="hidden" id="exampleGrid" value="" />
Modified jqgrid as
$(document).ready(function () {
$("#grid").jqGrid({
emptyrecords: "No records to view",
ignoreCase: true,
datatype: "json",
url: '#Url.Action("LoadData", "Home")',
mtype: "GET",
height: 'auto',
rowNum: 5,
rowList: [5, 10, 15, 20],
colNames: ['EmployeeId', 'EmployeeName', 'EmployeeCity'],
colModel: [
{ name: 'EmployeeId', index: 'EmployeeId', key: true, width: 200, sorttype: 'int' },
{ name: 'EmployeeName', index: 'EmployeeName', width: 200, sorttype: 'text' },
{ name: 'EmployeeCity', index: 'EmployeeCity', width: 200, sorttype: 'text' }
],
pager: '#pager',
sortname: 'EmployeeId',
viewrecords: true,
loadComplete: function () {
var page = $('#grid').jqGrid('getGridParam', 'page');
$("#exampleGrid").val(page);
},
onSortCol: function (index, iCol, sortOrder) {
$('#grid').jqGrid('setGridParam', {
page: $("#exampleGrid").val()
});
},
sortorder: "asc",
caption: "jqGrid Example"
}).navGrid("#pager",
{ search: false, refresh: false, add: false, edit: false, del: false },
{},
{},
{}
);
});

Sorting icon not updating on setting the sortorder

I am trying to change the sorting order of jqGrid by using this code:
jQuery('#id').setGridParam({sortorder:"desc"}).trigger("reloadGrid");
It changes the sortorder of the table but the Sorting Icon of the table is not changing as per the order. In onSortCol i'm sorting the column which actually sort the column. But when i use the above piece of code to set the sortorder, the sortorder is set but the sort icon still shows the previous sortorder.
_table.jqGrid({
datatype: 'local', // disable initial autoload. this will be when load function is called "json",
altRows: true,
altclass : 'AltRowClass',
gridView: true,
width:850,
height:"auto",
rowheight: 75,
align: 'center',
treeGrid: false,
loadonce:true,
ExpandColumn: 'name',
loadtext : 'Currently updating',
mtype : 'POST',
colNames: ['MSISDN','IMSI','Last name','First name','Device type','CE Index','Customer lifetime value'],
colModel: [
{ name: 'MSISDN', align: 'center', hidden: false, sortable: false,formatter: maskingColumn},
{ name: 'IMSI', align: 'center', hidden: false, sortable: false,formatter: maskingColumn},
{ name: 'LastName', align: 'center', hidden: false, sortable: false},
{ name: 'FirstName', align: 'center', hidden: false, sortable: false},
{ name: 'DeviceType', align: 'center', hidden: false, sortable: false,formatter: columnData},
{ name: 'CEIndex', align: 'center', hidden: false, sortable: true, sorttype: 'int'},
{ name: 'CustomerLifetimeValue', align: 'center', hidden: false, sortable: false}
],
sortname: 'CEIndex',
sortorder: 'desc',
loadComplete: function(data)
{
var rowCount = _table.jqGrid('getGridParam', 'records');
if (rowCount > 5) {
_table.parents("div.ui-jqgrid-bdiv").css({'max-height':'300px'});
_table.closest(".ui-jqgrid-bdiv").css({'overflow-y':'auto'}).css({'overflow-x':'hidden'});
}
if (rowCount != 0) {
_table.parents().find('.ui-jqgrid-view').first().show();
}
if (rowCount <= rowsNum) {
utils.find('cei-drill-customer-detail-showmore').hide();
} else {
utils.find('cei-drill-customer-detail-showmore').show();
}
_table.trigger("reloadGrid");
} ,
onSortCol: function (data, status, xhr) {
if (xhr == 'asc') {
var postData = this.p.postData.jsonRequest.replace('Top','Bottom');
actionInputObjectExportCustDrilldown.parameters.requestQuery = actionInputObjectExportCustDrilldown.parameters.requestQuery.replace('Top','Bottom');
var postDataVar = {
operation : 'drillDownLevel1',
drillLevel1 : "drilldown",
jsonRequest : postData
};
_this.load(postDataVar);
} else if (xhr == 'desc') {
var postData = this.p.postData.jsonRequest.replace('Bottom','Top');
actionInputObjectExportCustDrilldown.parameters.requestQuery = actionInputObjectExportCustDrilldown.parameters.requestQuery.replace('Bottom','Top');
var postDataVar = {
operation : 'drillDownLevel1',
drillLevel1 : "drilldown",
jsonRequest : postData
};
_this.load(postDataVar);
}
},
beforeProcessing : function(data, status, xhr) {
jQuery('div#jqgh_' + prefix + '-cei-dd-customer-details-table_CustomerLifetimeValue.ui-jqgrid-sortable').text("Customer Lifetime Value(" + filterValuesHl.currency + ")");
if (data.queryError != null || !data.rows || data.rows.length == 0) {
utils.find('cei-drill-customer-detail-ExportShowMore').hide();
utils.find('div-for-export-customer').hide();
var noError = utils.find('cei-customerDetails-div').parent().find(".cei-customer-details-dd-no-data");
if (data.queryError != null) {
noError.text("Error in portlet: " + data.queryError);
} else {
noError.html("<strong>No Data Available</strong>");
}
noError.show();
return false;
} else {
utils.find('cei-drill-customer-detail-ExportShowMore').show();
utils.find('div-for-export-customer').show();
utils.find('cei-drill-customer-detail-showmore').show();
//Hiding the columns which has no data in all the rows.
hideColumns(data);
//Setting CSV Data
csvData = data;
}
},
beforeRequest : function() {
_table.parents().find('.ui-jqgrid-view').first().hide();
utils.find('cei-customerDetails-div').parent().find(".cei-customer-details-dd-no-data").hide();
},
loadError : function(xhr, st, err) {
utils.find('cei-drill-customer-detail-ExportShowMore').hide();
utils.find('div-for-export-customer').hide();
var noError = utils.find('cei-customerDetails-div').parent().find(".cei-customer-details-dd-no-data");
noError.html("<html>Error connecting portlet: " + err + "</strong>");
noError.show();
}
});
You can try following code where id is your column name.
$('#grid').jqGrid('setGridParam', {sortorder: 'desc'});
$('#grid').jqGrid('sortGrid', 'id');

jqgrid add window parameter

I'm uwsing MVC and jqgrid and I need to pass a value from dropdownlist to add or edit window. this is my code:
View:
jQuery("#grid").jqGrid({
url: '#Url.Content("~/")' + 'Something/GridData/',
datatype: "json",
mtype: 'POST',
colNames: ['Type', 'Product', 'Value1', 'Value2', 'Value3'],
colModel: [
{ name: 'parType', index: 'parType', width: 80, align: 'center', sortable: false, editable: true, search: false,
editrules: { required: true, number: true },
editoptions: {
dataEvents: [{
type: 'keyup',
fn: function (e) {
if (this.value.match(/\D/)) this.value = this.value.replace(/\D/g, '');
}
}]
}
},
{ name: 'parProduct', index: 'parProduct', width: 80, align: 'left', editable: true, edittype: "select",
editrules: { required: true },
editoptions: {
multiple: false,
size: 1,
dataUrl: '#Url.Content("~/")' + 'Something/List/',
buildSelect: function (data) {
var response = jQuery.parseJSON(data);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
var ri = response[i];
s += '<option value="' + ri.Value + '">' + ri.Text + '</option>';
}
}
return s + "</select>";
}
}
},
{ name: 'parValue1', index: 'parValue1', width: 80, align: 'right', sortable: false, editable: true, search: false,
editrules: { required: true, number: true },
editoptions: {
dataEvents: [{
type: 'keyup',
fn: function (e) {
if (this.value.match(/\D/)) this.value = this.value.replace(/\D/g, '');
}
}]
}
},
{ name: 'parValue2', index: 'parValue2', width: 80, align: 'right', sortable: false, editable: true, search: false,
editrules: { required: true, number: true },
editoptions: {
dataEvents: [{
type: 'keyup',
fn: function (e) {
if (this.value.match(/\D/)) this.value = this.value.replace(/\D/g, '');
}
}]
}
},
{ name: 'parValue3', index: "parValue3", width: 80, align: 'right', editable: true,
editrules: { required: true },
editoptions: {
dataEvents: [{
type: 'blur',
fn: function (e) {
onBlurDecimal(this.id);
}
}]
}
}],
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery('#pager'),
sortname: '',
viewrecords: true,
sortorder: "asc",
caption: "Title",
height: 250,
width: 700
});
jQuery("#grid").jqGrid('navGrid', '#pager',
{ edit: false, add: true, del: true, search: false }, //options
{url: '#Url.Content("~/")' + 'Something/Add', closeAfterAdd: true, width: 500 }, // add options
{} // search options
);
#Html.ValidationSummary(False)
#Using Html.BeginForm()
<table>
<tr>
<td>
#Html.Label("ID_CONTRATANTE", "Contratante:")
#Html.DropDownListFor(Function(Model) Model.ID_CONTRATANTE, Nothing, New With {.style = "width:300px; visibility:visible", .class = "letraingreso"})
</td>
</tr>
</table>
End Using
Controller
Function Add(ByVal parType As Long, ByVal parProduct As Long, ByVal parValue1 As Long, ByVal parValue2 As Long, ByVal parValue3 As String) As ActionResult
Try
Dim varE As General1Entities = New General1Entities
Dim parIDContratante = Request.Form("ID_CONTRATANTE")
Dim var1 = New OBJECT With { _
.ID_TYPE = parProduct,
.ID_CONTRATANTE = parIDContratante,
.CODE = parType,
.VALUE1 = parValue1,
.VALUE2 = parValue2,
.VALUE3 = parValue3
}
varE.AddToOBJECTS(var1)
varE.SaveChanges()
Return Json(True)
Catch ex As Exception
Return Json(False)
End Try
End Function
As you can see, I need to get DDL value from main view (ID_CONTRATANTE) and put it into parIDContratante. Obviously the value return Nothing because the add window of jqgrid it's open. How can I send from parent view to add view window this value?
Regards.
Ok.... After looking for solutions I get it.
View (replace the old navGrid)
jQuery("#grid").jqGrid('navGrid', '#pager', {
edit: false, add: true, del: true, search: false, refresh: false
}, // general options
{
}, // options edit
{
url: '#Url.Content("~/")' + 'Something/WorkWith',
closeOnEscape: true,
closeAfterAdd: true,
width: 500,
modal: true,
addCaption: 'Nueva Tarifa',
reloadAfterSubmit: true,
beforeShowForm: function (frm) { $('#ID_CONTRATANTE').val(); },
//bottominfo: "Fields marked with (*) are required",
drag: true,
onclickSubmit: function (params) {
var ajaxData = {};
ajaxData = { parIDContratante: $("#ID_CONTRATANTE").val() };
return ajaxData;
}
}, // options add
{
url: "/Something/WorkWith"
}, // opciones para el dialogo de borrado
{
} // options search
);
Controller (replace old controller)
Function WorkWith(ByVal parFormCollection As FormCollection) As ActionResult
Try
Dim varE As General1Entities = New General1Entities
Dim operation = parFormCollection("oper")
If operation.Equals("add") Then
Dim var1 = New OBJECT With { _
.ID_TYPE = parFormCollection.Get("parProduct").ToString,
**.ID_CONTRATANTE = parFormCollection.Get("parIDContratante").ToString,**
.etc.....
}
varE.AddToOBJECTS(var1)
varE.SaveChanges()
ElseIf operation.Equals("edit") Then
ElseIf operation.Equals("del") Then
End If
Return Json(True)
Catch ex As Exception
' Do some error logging stuff, handle exception, etc.
Return Json(False)
End Try
End Function
I hope this helps some else.
Bye.

Resources