jqgrid add window parameter - asp.net-mvc-3

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.

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.

jqgrid inline editing autocomplete dropdown

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 });
});

JQGrid MultiSelect Filter option populate based on column's distinct value(part-II)

I am using this to fill multiselect filter value based on those are present in available rows for particular column.
I am facing below issue when going to delete selected row i.e. say I have deleted the first row, after deletion multiselect filter should recalculate the value based on those are present in available rows for particular column(for SkillCategory). We can see after deletion first row still "Data" value is available for SkillCategory multiselect filter.
How can I recalculate multiselect filter value after deleting row/add/update?
<script type="text/javascript">
function loadCompleteHandler1() {
initializeGridFilterValueSupply();
}
jQuery(function () {
$.extend(true, $.jgrid.search, {
beforeShowForm: function ($form) {
$form.closest(".ui-jqdialog").position({
of: window,
at: "center center",
my: "center center"
});
}
});
$.extend($.jgrid.edit, { viewPagerButtons: false });
$grid = $("#listTableSupply"),
myDefaultSearch = "cn",
getColumnIndexByName = function (columnName) {
var cm = $(this).jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i += 1) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
},
modifySearchingFilter = function (separator) {
var i, l, rules, rule, parts, j, group, str, iCol, cmi, cm = this.p.colModel,
filters = $.parseJSON(this.p.postData.filters);
if (filters && filters.rules !== undefined && filters.rules.length > 0) {
rules = filters.rules;
for (i = 0; i < rules.length; i++) {
rule = rules[i];
iCol = getColumnIndexByName.call(this, rule.field);
cmi = cm[iCol];
if (iCol >= 0 &&
((cmi.searchoptions === undefined || cmi.searchoptions.sopt === undefined)
&& (rule.op === myDefaultSearch)) ||
(typeof (cmi.searchoptions) === "object" &&
$.isArray(cmi.searchoptions.sopt) &&
cmi.searchoptions.sopt[0] === rule.op)) {
// make modifications only for the 'contains' operation
parts = rule.data.split(separator);
if (parts.length > 1) {
if (filters.groups === undefined) {
filters.groups = [];
}
group = {
groupOp: 'OR',
groups: [],
rules: []
};
filters.groups.push(group);
for (j = 0, l = parts.length; j < l; j++) {
str = parts[j];
if (str) {
// skip empty '', which exist in case of two separaters of once
group.rules.push({
data: parts[j],
op: rule.op,
field: rule.field
});
}
}
rules.splice(i, 1);
i--; // to skip i++
}
}
}
this.p.postData.filters = JSON.stringify(filters);
}
},
dataInitMultiselect = function (elem) {
setTimeout(function () {
var $elem = $(elem), id = elem.id,
inToolbar = typeof id === "string" && id.substr(0, 3) === "gs_",
options = {
selectedList: 2,
height: "auto",
checkAllText: "all",
uncheckAllText: "no",
noneSelectedText: "Any",
open: function () {
var $menu = $(".ui-multiselect-menu:visible");
$menu.width("auto");
return;
}
},
$options = $elem.find("option");
if ($options.length > 0 && $options[0].selected) {
$options[0].selected = false; // unselect the first selected option
}
if (inToolbar) {
options.minWidth = 'auto';
}
//$elem.multiselect(options);
$elem.multiselect(options).multiselectfilter({ placeholder: '' });
$elem.siblings('button.ui-multiselect').css({
width: inToolbar ? "98%" : "100%",
marginTop: "1px",
marginBottom: "1px",
paddingTop: "3px"
});
}, 50);
};
jQuery("#listTableSupply").jqGrid({
url: 'HttpHandler/SupplyHandler.ashx',
ajaxSelectOptions: { cache: false },
postData: { ActionPage: 'TransportType', Action: 'Fill' },
datatype: 'json',
mtype: 'GET',
colNames: ['SupplyId', 'Account', 'AccountPOC', 'COE', 'Type', 'Location', 'EmpId', 'EmpName', 'Designation', 'AvailabilityDate', 'AvailabilityMonth', 'Exp', 'SkillCategory', 'PrimarySkill', 'SecondarySkill', 'OtherSkill', 'Role', 'VisaStatus', 'Country', 'Comments'],
colModel: [
{ name: 'SupplyId', index: 'SupplyId', width: '5%', align: 'center', sortable: true, resizable: true, hidden: true },
{
name: 'Account', index: 'Account', width: '10%', sortable: true, resizable: true, stype: 'select'
},
{ name: 'AccountPOC', index: 'AccountPOC', width: '5%', sortable: true, resizable: true, hidden: true },
{
name: 'COE', index: 'COE', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'Type', index: 'Type', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'Location', index: 'Location', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{ name: 'EmpId', index: 'EmpId', width: '5%', sortable: true, resizable: true, hidden: true },
{ name: 'EmpName', index: 'EmpName', width: '5%', sortable: true, resizable: true, hidden: true },
{
name: 'Designation', index: 'Designation', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'AvailabilityDate', index: 'AvailabilityDate', width: '5%', sortable: true, search: true, resizable: true, stype: 'select'
},
{ name: 'AvailabilityMonth', index: 'AvailabilityMonth', width: '5%', sortable: true, resizable: true, hidden: true },
{
name: 'Experience', index: 'Experience', width: '5%', sortable: true, resizable: true, search: true, stype: 'select'
},
{
name: 'SkillCategory', index: 'SkillCategory', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'PrimarySkill', index: 'PrimarySkill', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'SecondarySkill', index: 'SecondarySkill', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'OtherSkill', index: 'OtherSkill', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'CurrentRole', index: 'CurrentRole', width: '5%', sortable: true, resizable: true,
stype: 'select'
},
{
name: 'VisaStatus', index: 'VisaStatus', width: '5%', sortable: true, resizable: true,
stype: 'select'
},
{
name: 'Country', index: 'Country', width: '5%', sortable: true, resizable: true,
stype: 'select'
},
{ name: 'Comments', index: 'Comments', width: '5%', search: false, sortable: false, resizable: true },
],
width: '1192',
height: '300',
loadonce: true,
pager: '#pagerSupply',
gridview: true,
rowNum: 15,
rowList: [15, 30, 45],
rowTotal: 5000,
sortorder: 'asc',
ignoreCase: true,
sortname: 'Account',
viewrecords: true,
rownumbers: true,
toppager: true,
caption: 'Supply',
emptyrecords: "No records to view",
loadtext: "Loading...",
refreshtext: "Refresh",
refreshtitle: "Reload Grid",
loadComplete: loadCompleteHandler1,
ondblClickRow: function (rowid) {
jQuery(this).jqGrid('viewGridRow', rowid);
},
beforeRequest: function () //loads the jqgrids state from before save
{
modifySearchingFilter.call(this, ',');
}
}).jqGrid('bindKeys');
$('#listTableSupply').bind('keydown', function (e) {
if (e.keyCode == 38 || e.keyCode == 40) e.preventDefault();
});
//setSearchSelect("SkillCategory");
$('#listTableSupply').jqGrid('navGrid', '#pagerSupply', {
cloneToTop: true,
refresh: true, refreshtext: "Clear Filter", edit: false, add: false, del: true, search: false
}, {}, {}, {//Del
closeOnEscape: true, //Closes the popup on pressing escape key
drag: true,
recreateForm: true,
//closeAfterEdit: true,
url: 'HttpHandler/SupplyHandler.ashx',
delData: {
ActionPage: 'TransportType', Action: 'Delete',
SupplyId: function () {
var sel_id = $('#listTable').jqGrid('getGridParam', 'selrow');
var value = $('#listTable').jqGrid('getCell', sel_id, 'SupplyId');
return value;
}
},
afterShowForm: function ($form) {
$form.closest(".ui-jqdialog").position({ of: window, my: "center center", at: "center center" });
//$form.closest(".ui-jqdialog").position({of: window,at: "center center",my: "left top"});
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
//$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after del
return [true, '']
}
else {
if (response.responseText == "Record Successfully Deleted!!!") {
//$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
var myInfo = '<div class="ui-state-highlight ui-corner-all">' +
'<span class="ui-icon ui-icon-info" ' +
'style="float: left; margin-right: .3em;"></span>' +
'<span>Record Successfully Deleted!!!</span></div>';
var infoTR = $("table#TblGrid_listTable>tbody>tr.tinfo");
infoTD = infoTR.children("td.topinfo");
infoTD.html(myInfo);
infoTR.show();
setTimeout(function () {
infoTD.children("div").fadeOut('slow',
function () {
infoTR.hide();
});
}, 8000);
initializeGridFilterValueSupply();
return [true, '']
}
else {
return [false, response.responseText]//Captures and displays the response text on th Del window
}
}
}
}, {
multipleSearch: true,
multipleGroup: true,
recreateFilter: true
});
jQuery("#listTableSupply").jqGrid('navButtonAdd', '#listTableSupply_toppager_left', { // "#list_toppager_left"
caption: "Refresh",
buttonicon: 'ui-icon-refresh',
onClickButton: function () {
$("#listTableSupply").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid", [{ page: 1 }]);
initializeGridFilterValueSupply();
}
});
jQuery("#listTableSupply").jqGrid('navButtonAdd', '#pagerSupply', { // "#list_toppager_left"
caption: "Refresh",
buttonicon: 'ui-icon-refresh',
onClickButton: function () {
$("#listTableSupply").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid", [{ page: 1 }]);
initializeGridFilterValueSupply();
}
});
});
//]]>
</script>
<script type="text/javascript">
initializeGridFilterValueSupply = function () {
jQuery("#listTableSupply").jqGrid('destroyGroupHeader');
setSearchSelect("Account", jQuery("#listTableSupply"));
setSearchSelect("COE", jQuery("#listTableSupply"));
setSearchSelect("AccountPOC", jQuery("#listTableSupply"));
setSearchSelect("Type", jQuery("#listTableSupply"));
setSearchSelect("Location", jQuery("#listTableSupply"));
setSearchSelect("Designation", jQuery("#listTableSupply"));
setSearchSelect("EmpName", jQuery("#listTableSupply"));
setSearchSelect("AvailabilityDate", jQuery("#listTableSupply"));
setSearchSelect("Experience", jQuery("#listTableSupply"));
setSearchSelect("SkillCategory", jQuery("#listTableSupply"));
setSearchSelect("PrimarySkill", jQuery("#listTableSupply"));
setSearchSelect("SecondarySkill", jQuery("#listTableSupply"));
setSearchSelect("OtherSkill", jQuery("#listTableSupply"));
setSearchSelect("CurrentRole", jQuery("#listTableSupply"));
setSearchSelect("VisaStatus", jQuery("#listTableSupply"));
setSearchSelect("Country", jQuery("#listTableSupply"));
jQuery("#listTableSupply").jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: true,
defaultSearch: myDefaultSearch,
beforeClear: function () {
$(this.grid.hDiv).find(".ui-search-toolbar .ui-search-input>select[multiple] option").each(function () {
this.selected = false; // unselect all options
});
$(this.grid.hDiv).find(".ui-search-toolbar button.ui-multiselect").each(function () {
$(this).prev("select[multiple]").multiselect("refresh");
}).css({
width: "98%",
marginTop: "1px",
marginBottom: "1px",
paddingTop: "3px"
});
}
});
jQuery("#listTableSupply").jqGrid('setGridHeight', 300);
}
</script>
I got my answer.
I need to use destroyFilterToolbar to destroy the filter toolbar and then create the toolbar one more time using filterToolbar.
initializeGridFilterValueDemand = function () {
//jQuery("#listTableSupply").jqGrid('destroyGroupHeader');
setSearchSelect("AccountName", jQuery("#listTableDem"));
setSearchSelect("COE", jQuery("#listTableDem"));
setSearchSelect("DemandType", jQuery("#listTableDem"));
setSearchSelect("Location", jQuery("#listTableDem"));
setSearchSelect("Designation", jQuery("#listTableDem"));
setSearchSelect("Experience", jQuery("#listTableDem"));
setSearchSelect("ExpectedRole", jQuery("#listTableDem"));
setSearchSelect("SkillCategory", jQuery("#listTableDem"));
setSearchSelect("PrimarySkill", jQuery("#listTableDem"));
setSearchSelect("SecondarySkill", jQuery("#listTableDem"));
setSearchSelect("OtherSkill", jQuery("#listTableDem"));
setSearchSelect("RequiredDate", jQuery("#listTableDem"));
setSearchSelect("CriticalFlag", jQuery("#listTableDem"));
setSearchSelect("ConfidenceFactor", jQuery("#listTableDem"));
setSearchSelect("HiringSOId", jQuery("#listTableDem"));
**jQuery("#listTableDem").jqGrid("destroyFilterToolbar");**
jQuery("#listTableDem").jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: true,
defaultSearch: myDefaultSearch,
beforeClear: function () {
$(this.grid.hDiv).find(".ui-search-toolbar .ui-search-input>select[multiple] option").each(function () {
this.selected = false; // unselect all options
});
$(this.grid.hDiv).find(".ui-search-toolbar button.ui-multiselect").each(function () {
$(this).prev("select[multiple]").multiselect("refresh");
}).css({
width: "98%",
marginTop: "1px",
marginBottom: "1px",
paddingTop: "3px"
});
}
});
jQuery("#listTableDem").jqGrid('setGridHeight', 300);
}
And I am calling it in loadComplete event.
Update:
This will not going to work if we use destroyGroupHeader

Server-side function is called only once in jqGrid

I've put a jqgrid the page. In Jqgrid placed a column that I want when user click on the column, Fill Other Jqgrid.Now when I click on the desired column. Only first-time Fill second JQGrid,But the next time the server side code will not run.
The code is written as follows
var firstButtonColumnIndex = 0;
grid = $('#list'); buttonNames = {};
grid.jqGrid({
url: 'jQGridHandler.ashx?Request=1',
loadonce: true,
direction: "rtl",
pgtext: "صفحه {0} از {1}",
datatype: 'json',
height: 250,
colNames: ['شماره درخواست', 'شماره اموال', 'شرح دستور کار', 'تاریخ دستور کار', 'زمان دستور کار', 'ملاحظات', '', ''],
colModel: [
{ name: 'WorkOrderNo', width: 100, sortable: true },
{ name: 'AssetNo', width: 100, sortable: true },
{ name: 'WorkDescription', width: 400, sortable: true },
{ name: 'WorkOrderDate', width: 80, sortable: true },
{ name: 'WorkOrderTime', width: 80, sortable: true },
{ name: 'Remark', width: 100, sortable: true },
{ name: 'del', width: 20, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-trash'></span>";
}
},
{ name: 'details', width: 20, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-document'></span>";
}
}
],
gridview: true,
rowNum: 10,
rowList: [10, 20, 30],
pager: '#pager',
// sortname: 'WorkOrderNo',
viewrecords: true,
sortorder: 'asc',
caption: 'درخواست ها...........',
rownumbers: true,
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 7) {
//alert("rowid=" + rowid + "\nButton name: " + buttonNames[iCol]);
// $('img').each(function () {
$("#workRequestPopUp").draggable();
// });
} else if (iCol == 8) {
workOrderId = rowid;
$("#tblRequestWorks tr").remove();
$("#tblRequestWorks").jqGrid({
// url: 'jQGridHandler.ashx?RequestWorksFill=1&workOrderId=' + workOrderId,
url: "PublicHandler.ashx?Request=1&workOrderId: rowid",
direction: "rtl",
pgtext: "",
datatype: 'json',
height: 250,
colNames: ['نام کار', 'نام واحد', 'سرپرست واحد', 'تعداد', 'پایان کار', ''],
colModel: [
{ name: 'WorkName', width: 300, sortable: true },
{ name: 'SectionName', width: 100, sortable: true },
{ name: 'SectionSupervisor', width: 100, sortable: true },
{ name: 'RequestCount', width: 80, sortable: true },
{ name: 'FinishWork', width: 100, sortable: true },
{ name: 'details', width: 20, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-document'></span>";
}
}
],
rowNum: 10,
rowList: [10, 20, 30],
sortorder: 'asc',
caption: 'Test',
rownumbers: true,
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 6) {
alert(rowid);
Fill12(rowid);
} else if (iCol == 8) {
alert(rowid);
Fill12(rowid);
return true;
// return (iCol >= firstButtonColumnIndex) ? false : true;
}
},
dataType: "json"
});
// fillRequestWorkPopup(workOrderId);
popup(e);
}
// prevent row selection if one click on the button
// return (iCol >= firstButtonColumnIndex) ? false : true;
return true;
}
});
It is Delegate Function in tr in JQGrid?
I respected professors can help. thanks All
The URL "PublicHandler.ashx?Request=1&workOrderId: rowid" seems me wrong. Do you mean probably "PublicHandler.ashx?Request=1&workOrderId=" + rowid? The better will be to use url: "PublicHandler.ashx" with postData: {Request: 1, workOrderId: rowid}.
The next problem is the usage of $("#tblRequestWorks tr").remove();. You don't included any HTML code which you use on the page. If you want to destroy the old grid and create a new one on the same place you should use GridUnload instead of $("#tblRequestWorks tr").remove();: $("#tblRequestWorks").jqGrid('GridUnload'); (see here and example).
You can also remove dataType: "json" from the code. jqGrid don't know the option and you already use the correct datatype: "json" option.
I think you can change your code so that the usage of GridUnload will be not needed. Only changing on some parameters of the second grid ($("#tblRequestWorks")) and reloading it with respect of $("#tblRequestWorks").trigger('reloadGrid', [{page: 1}]); seems me enough.
One more remark: you should be very careful in the id values for the second grid. It is not permitted to have id duplicates on the page. If you can't generate unique ids on the server you can consider to use idPrefix option of the grid.

jqgrid apply filter after reload?

Am using jqgrid, loading data once, sorting and filtering locally and doing a refresh after each update/insert/delete. It works fine, besides that if I am using a filter (on top of grid), the filter remains the same after refresh, but the filter is not re-applied on the newly loaded data.
I have tried to call mygrid[0].triggerToolbar() after reloading grid with trigger('reloadGrid'), but there is no effect.
Thanks for any help or pointers :-)
Code below:
var lastsel;
var mygrid;
var currentLang;
//setup grid with columns, properties, events
function initGrid(lang, productData, resellerData, resellerSearchData) {
mygrid = jQuery("#list2").jqGrid({
//data loading settings
url: '/public/Gadgets/LinkGadget/ProductLinks/' + lang,
editurl: "/public/Gadgets/LinkGadget/Edit/" + lang,
datatype: "json",
mtype: 'POST',
jsonReader: {
root: "rows",
cell: "",
page: "currpage",
//total: "totalrecords",
repeatitems: false
},
loadError: function (xhr, status, error) { alert(status + " " + error); },
//column definitions
colNames: ['Id', 'ProductId', 'Reseller Name', 'Link', 'Link Status'],
colModel: [
{ name: 'Id', index: 'Id', width: 40, sortable: false, resizable: true, editable: false, search: false, key: true, editrules: { edithidden: true }, hidden: true },
{ name: 'ProductId', index: 'ProductId', width: 190, sortable: true, sorttype: 'text', resizable: true, editable: true, search: true, stype: 'select', edittype: "select", editoptions: { value: productData }, editrules: { required: true} },
{ name: 'ResellerName', indexme: 'ResellerName', width: 190, sortable: false, sorttype: 'text', resizable: true, editable: true, search: true, stype: 'select', edittype: "select", editoptions: { value: resellerData }, editrules: { required: true }, searchoptions: { sopt: ['eq'], value: resellerSearchData} },
{ name: 'Link', index: 'Link', width: 320, sortable: true, sorttype: 'text', resizable: true, editable: true, search: true, edittype: "textarea", editoptions: { rows: "3", cols: "50" }, editrules: { required: true }, searchoptions: { sopt: ['cn']} },
{ name: 'LinkStatus', index: 'LinkStatus', width: 100, sortable: false, resizable: true, editable: false, search: false, formatter: linkStatusFormatter}],
//grid settings
//rowList: [10, 25, 50],
rowNum: 20,
pager: '#pager2',
sortname: 'ProductId',
sortorder: 'asc',
height: '100%',
viewrecords: true,
gridview: true,
loadonce: true,
viewsortcols: [false, 'vertical', true],
caption: " Product links ",
//grid events
onSelectRow: function (id) {
if (id && id !== lastsel) {
if (lastsel == "newid") {
jQuery('#list2').jqGrid('delRowData', lastsel, true);
}
else {
jQuery('#list2').jqGrid('restoreRow', lastsel);
}
jQuery('#list2').jqGrid('editRow', id, true, null, afterSave); //reload on success
lastsel = id;
}
},
gridComplete: function () {
//$("#list2").setGridParam({ datatype: 'local', page: 1 });
$("#pager2 .ui-pg-selbox").val(25); //changing the selected values triggers paging to work for some reason
}
});
//page settings
jQuery("#list2").jqGrid('navGrid', '#pager2',
{ del: false, refresh: false, search: false, add: false, edit: false }
);
//refresh grid button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Refresh", title: "Refresh grid", buttonicon: 'ui-icon-refresh',
onClickButton: function () {
reload();
}
});
//clear search button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Clear search", title: "Clear Search", buttonicon: 'ui-icon-refresh',
onClickButton: function () {
mygrid[0].clearToolbar();
}
});
//add row button
jQuery("#list2").jqGrid('navButtonAdd', '#pager2', { caption: "New", buttonicon: 'ui-icon-circle-plus',
onClickButton: function (id) {
var datarow = { Id: "newid", ProductId: "", ResellerName: "", Link: "" };
jQuery('#list2').jqGrid('restoreRow', lastsel); //if editing other row, cancel this
lastsel = "newid"; // id;
var su = jQuery("#list2").addRowData(lastsel, datarow, "first");
if (su) {
jQuery('#list2').jqGrid('editRow', lastsel, true, null, afterSave); //reload on success
jQuery("#list2").setSelection(lastsel, true);
}
},
title: "New row"
});
//delete row button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Delete", title: "Delete row", buttonicon: 'ui-icon-circle-minus',
onClickButton: function () {
if (lastsel) {
if (confirm('Are you sure you want to delete this row?')) {
var url = '/public/Gadgets/LinkGadget/Edit/' + currentLang;
var data = { oper: 'del', id: lastsel };
$.post(url, data, function (data, textStatus, XMLHttpRequest) {
reload();
});
lastsel = null;
}
else {
jQuery("#list2").resetSelection();
}
}
else {
alert("No row selected to delete.");
}
}
});
jQuery("#list2").jqGrid('filterToolbar');
}
//Used by initGrid - formats link status column by adding button
function linkStatusFormatter(cellvalue, options, rowObject) {
if (rowObject.Id != "newrow")
return "<input style='height:22px;width:90px;' type='button' " + "value='Check link' " + "onclick=\"CheckLink(this, '" + rowObject.Id + "'); \" />";
else
return "";
}
//Used by initGrid - reloads grid
function reload() {
//jqgrid setting "loadonce: true" will reset datatype from json to local after grid has loaded. "datatype: local"
// does not allow server reloads, therefore datatype is reset before trying to reload grid
$("#list2").setGridParam({ datatype: 'json' }).trigger('reloadGrid');
//mygrid[0].clearToolbar();
lastsel = null;
//Comments: after reload, toolbar filter is not applied to refreshed data. Tried row below without luck
//mygrid[0].triggerToolbar();
}
//after successful save, reload grid and deselect row
function afterSave() {
reload();
}
Your data is not getting re binded to the grid after save/update delete

Resources