Related
I can't get the grid to populate my data. The correct number of rows shows up, but everything is empty (in my case, 8 empty rows). I am using jqGrid-free 4.15.5, jQueryUI 1.21.1, jQuery 3.5.1.
Is there something simple that I'm doing wrong?
Some things that are important to me:
loadonce: true (so that I get my dataset one time and do client sorting from there)
forceClientSorting: true
Also, I've seen varying solutions to pagers, so I'm not sure if I'm doing that correctly. From what I understand, simply setting pager: true should be sufficient with this version of jqGrid.
Controller Action:
public IActionResult GridData(string sidx, string sord, int page, int rows)
{
int pageIndex = page - 1;
int pageSize = rows;
List<SubCampaignData> subCampaignData = new List<SubCampaignData>();
subCampaignData = database.SubCampaignData
.Include(scd => scd.ContentPriority)
.Include(scd => scd.DataSources)
.Include(scd => scd.DeliveryMethod)
.Include(scd => scd.DeliveryPriority)
.Include(scd => scd.Contacts)
.ThenInclude(c => c.Role)
.ToList();
var sortColumn = typeof(SubCampaignData).GetProperty(sidx);
if (sord.ToUpper() == "ASC")
{
subCampaignData = subCampaignData.OrderBy(scd => sortColumn.GetValue(scd, null)).ToList();
}
else
{
subCampaignData = subCampaignData.OrderByDescending(scd => sortColumn.GetValue(scd, null)).ToList();
}
var gridData = subCampaignData.Select(scd => new
{
Campaign = scd.Campaign,
SubCampaign = scd.SubCampaign,
BulkCampaignName = scd.BulkCampaignName,
DeliveryMethodName = scd.DeliveryMethod.DeliveryMethodName,
AutomationTriggerName = scd.AutomationTriggerName,
MasterDataExtension = scd.MasterDataExtension,
Purpose = scd.Purpose,
Active = scd.Active.ToString(),
FailureContactName = string.Join(';', scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "FAILURE CONTACT").Select(c => c.Name).ToList()),
DeliveryPriorityName = scd.DeliveryPriority.PriorityName,
ContentPriorityName = scd.ContentPriority.PriorityName,
EscalateAfter = scd.EscalateAfter,
ClientName = string.Join(';', scd.DataSources.Select(ds => ds.ClientName).ToList()),
SourceJob = scd.SourceJob,
MainframeFileName = scd.MainframeFileName,
AggregationJob = scd.AggregationJob,
AggregationRunTime = scd.AggregationRunTime,
SendTime = scd.SendTime,
RunFrequency = scd.RunFrequency,
RunDays = scd.RunDays,
RunMonths = scd.RunMonths,
SendPend = scd.SendPend,
SendPendDelay = scd.SendPendDelay,
SendPendReason = scd.SendPendReason,
RegressionScripts = scd.RegressionScripts.ToString(),
ConfirmedActiveDate = FormatNullableDateTime(scd.ConfirmedActiveDate),
StartDate = FormatNullableDateTime(scd.StartDate),
Resend = scd.Resend,
ResendAbility = scd.ResendAbility.ToString(),
RecreateAbility = scd.RecreateAbility.ToString(),
ResendRecreateDetails = scd.ResendRecreateDetails,
BusinessOwnerName = string.Join(';', scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "BUSINESS OWNER").Select(c => c.Name).ToList()),
BusinessSponsorName = string.Join(';', scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "BUSINESS SPONSOR").Select(c => c.Name).ToList()),
BusinessSponsorEmailAddress = string.Join(';', scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "BUSINESS SPONSOR").Select(c => c.EmailAddress).ToList()),
BusinessSponsorConfirmedDate = string.Join(';', FormatNullableDateTimes(scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "BUSINESS SPONSOR").Select(c => c.ConfirmedDate).ToList())),
FailureContactEmailAddress = string.Join(';', scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "FAILURE CONTACT").Select(c => c.EmailAddress).ToList()),
FailureContactConfirmedDate = string.Join(';', FormatNullableDateTimes(scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "FAILURE CONTACT").Select(c => c.ConfirmedDate).ToList())),
SmeAnalystName = string.Join(';', scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "SME/ANALYST").Select(c => c.Name).ToList()),
SmeAnalystEmailAddress = string.Join(';', scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "SME/ANALYST").Select(c => c.EmailAddress).ToList()),
SmeAnalystConfirmedDate = string.Join(';', FormatNullableDateTimes(scd.Contacts.Where(c => c.Role.RoleName.ToUpper() == "SME/ANALYST").Select(c => c.ConfirmedDate).ToList())),
}).ToArray();
return Json(gridData);
}
View (grid function):
$(function () {
"use strict";
var mydata = [
{ id: "10", campaign: "Agent AutoReply Emails", subcampaign: "FAO_Agent_Inhouse_SoldQuote", commdeliverycampaign: "", deliverymethod: "Triggered Send", automationtriggeredsend: "Agent_AutoReply", masterdataextension: "Agent_AutoReply", purpose: "Sent to Agency when PGR has written new business for a customer on the Agency's behalf", active: "true", failurecontact: "", deliverypriority: "Medium", contentpriority: "Medium", escalateafter: "2", datasource: "Probill", sourcejob: "", mainframefile: "", inputfile: "", aggregationjob: "", aggregationruntime: "", sendtime: "Real-time", runfrequency: "Daily", rundays: "SMTWThFSa", runmonths: "JanFebMarAprMayJunJulAugSepOctNovDec", sendpend: "N", sendpenddelay: "", sendpendreason: "", regression: "false", confirmactivedate: "2020-07-22", startdate: "", resend: "", resendability: "false", recreateability: "true", resendcomments: "Can recreate the list of Agencies from a report for the date.", businessowner: "", businesssponsor: "Dan Merk;Patrick D Astolfo", sponsoremail: "Dan_Merk#progressive.com;Patrick_DAstolfo#progressive.com", sponsorconfirmdate: "2020-01-30", failureemail: "", failureconfirmdate: "", smeanalyst: "", smeanalystemail: "", smeanalystconfirmed: "", metadata: "" }
],
initDateEdit = function (elem, options) {
// we need get the value before changing the type
var orgValue = $(elem).val(), newformat,
cm = $(this).jqGrid("getColProp", options.name);
$(elem).attr("type", "date");
if ((Modernizr && !Modernizr.inputtypes.date) || $(elem).prop("type") !== "date") {
// if type="date" is not supported call jQuery UI datepicker
$(elem).css({ width: "8em" }).datepicker({
dateFormat: "yy-mm-dd",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: false
});
} else {
// convert date to ISO
if (orgValue !== "") {
newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
cm.formatoptions.newformat :
$(this).jqGrid("getGridRes", "formatter.date.newformat");
$(elem).val($.jgrid.parseDate.call(this, newformat, orgValue, "yy-mm-dd"));
}
$(elem).css("width", "11em");
}
},
initDateSearch = function (elem) {
setTimeout(function () {
$(elem).datepicker({
dateFormat: "yy-mm-dd",
autoSize: true,
changeYear: true,
changeMonth: true,
showWeek: false,
showButtonPanel: true
});
}, 50);
},
numberTemplate = {
formatter: "number", align: "right", sorttype: "number",
editrules: { number: true, required: true },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge", "nu", "nn", "in", "ni"] }
};
$("#list").jqGrid({
url: "/Home/GridData",
datatype: "json",
//data: mydata,
mtype: "GET",
colModel: [
{ name: "act", template: "actions", frozen: true },
{ name: "Campaign", label: "Campaign Name", width: 120, editable: false, frozen: true },
{ name: "SubCampaign", label: "SubCampaign Name", width: 141, editable: true, frozen: true },
{
name: "BulkCampaignName", label: "Bulk Campaign", width: 120,
editrules: { edithidden: true }, editable: true, hidden: true
},
{
name: "DeliveryMethodName", label: "Delivery Method", width: 120, formatter: "select",
formatoptions: { value: "Adhoc Bulk, Bulk, Bulk Text Messaging, Triggered Send, Triggered Text Messaging", defaultvalue: "Bulk" },
stype: "select",
searchoptions: { value: ":Any;Adhoc Bulk:Adhoc Bulk;Bulk:Bulk;Bulk Text Messaging:Bulk Text Messaging;Triggered Send:Triggered Send;Triggered Text Messaging:Triggered Text Messaging" },
editable: true
},
{ name: "AutomationTriggerName", label: "Automation/Triggered Send", width: 185, editable: true },
{ name: "MasterDataExtension", label: "Master Data Extension", width: 155, editable: true },
{ name: "Purpose", label: "Purpose", width: 155, editable: true },
{
name: "Active", label: "Active", width: 120, align: "center", formatter: "checkbox",
stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;true:Yes;false:No" },
editable: true,
edittype: "checkbox", editoptions: { value: "Yes:No", defaultValue: "Yes" }
},
{ name: "FailureContactName", label: "Failure Contact", width: 155, editable: true },
{
name: "DeliveryPriorityName", label: "Delivery Priority", width: 120, formatter: "select",
formatoptions: { value: "Low, Low-Medium, Medium, Medium-High, High", defaultvalue: "Medium" },
editable: true
},
{
name: "ContentPriorityName", label: "Content Priority", width: 120, formatter: "select",
formatoptions: { value: "Low, Low-Medium, Medium, Medium-High, High", defaultvalue: "Medium" },
editable: true
},
{ name: "EscalateAfter", label: "Escalate After (days)", width: 120, editable: true },
{ name: "ClientName", label: "Data Source", width: 100, editable: true },
{ name: "SourceJob", label: "Source Job", width: 120, editable: true },
{ name: "MainframeFileName", label: "Mainframe File", width: 120, editable: true },
{ name: "AggregationJob", label: "AggregationJob", width: 120, editable: true },
{ name: "AggregationRunTime", label: "Aggregation Run Time", width: 120, editable: true },
{ name: "SendTime", label: "Send Time", width: 120, editable: true },
{ name: "RunFrequency", label: "Run Frequency", width: 120, editable: true },
{ name: "RunDays", label: "Run Days", width: 120, editable: true },
{ name: "RunMonths", label: "Run Months", width: 120, editable: true },
{ name: "SendPend", label: "SendPend", width: 120, editable: true },
{ name: "SendPendDelay", label: "SendPend Delay", width: 120, editable: true },
{ name: "SendPendReason", label: "SendPend Reason", width: 120, editable: true },
{
name: "RegressionScripts", label: "Regression Scripts", width: 120, align: "center", formatter: "checkbox",
stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;true:Yes;false:No" },
editable: true,
edittype: "checkbox", editoptions: { value: "true:false", defaultValue: "false" }
},
{
name: "ConfirmedActiveDate", label: "Last Confirmed Active", width: 120, align: "center", sorttype: "date",
formatter: "date", formatoptions: { newformat: "Y-m-d" }, editable: true,
editoptions: { dataInit: initDateEdit },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDateSearch }
},
{
name: "StartDate", label: "Start Date", width: 120, align: "center", sorttype: "date",
formatter: "date", formatoptions: { newformat: "Y-m-d" }, editable: true,
editoptions: { dataInit: initDateEdit },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDateSearch }
},
{ name: "Resend", label: "Resend", width: 120, editable: true },
{
name: "ResendAbility", label: "Business Can Resend", width: 120, align: "center", formatter: "checkbox",
stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;true:Yes;false:No" },
editable: true,
edittype: "checkbox", editoptions: { value: "true:false", defaultValue: "false" }
},
{
name: "RecreateAbility", label: "Business Can Recreate", width: 120, align: "center", formatter: "checkbox",
stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;true:Yes;false:No" },
editable: true,
edittype: "checkbox", editoptions: { value: "true:false", defaultValue: "false" }
},
{ name: "ResendRecreateDetails", label: "Resend/Recreate Details", width: 120, editable: true },
{ name: "BusinessOwnerName", label: "Business Platform Owner", width: 120, editable: true },
{ name: "BusinessSponsorName", label: "Business Sponsor", width: 120, editable: true },
{ name: "BusinessSponsorEmailAddress", label: "Sponsor Email", width: 120, editable: true },
{
name: "BusinessSponsorConfirmedDate", label: "Sponsor Confirmed", width: 120, align: "center", sorttype: "date",
formatter: "date", formatoptions: { newformat: "Y-m-d" }, editable: true,
editoptions: { dataInit: initDateEdit },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDateSearch }
},
{ name: "FailureContactEmailAddress", label: "Failure Email", width: 120, editable: true },
{
name: "FailureContactConfirmedDate", label: "Failure Confirmed", width: 120, align: "center", sorttype: "date",
formatter: "date", formatoptions: { newformat: "Y-m-d" }, editable: true,
editoptions: { dataInit: initDateEdit },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDateSearch }
},
{ name: "SmeAnalystName", label: "SME/Analyst", width: 120, editable: true },
{ name: "SmeAnalystEmailAddress", label: "SME/Analyst Email", width: 120, editable: true },
{
name: "SmeAnalystConfirmedDate", label: "SME/Analyst Confirmed", width: 120, align: "center", sorttype: "date",
formatter: "date", formatoptions: { newformat: "Y-m-d" }, editable: true,
editoptions: { dataInit: initDateEdit },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDateSearch }
}
],
loadonce: true,
forceClientSorting: true,
cmTemplate: { autoResizable: true },
autoResizing: { compact: false, adjustGridWidth: false },
shrinkToFit: false,
autowidth: true,
rownumbers: true,
ignoreCase: true,
height: "auto",
sortname: "Campaign",
sortorder: "asc",
threeStateSort: true,
sortable: true,
pager: true,
rowNum: 10,
viewrecords: true,
searching: {
defaultSearch: "cn"
},
multiSort: true,
formEditing: {
onclickSubmit: function (options, postdata, formOper) {
return {};
}
}
}).jqGrid("setFrozenColumns")
.jqGrid("navGrid", { add: true, edit: true, del: true })
.jqGrid("inlineNav", { add: false, edit: false })
.jqGrid("filterToolbar")
.jqGrid("gridResize");
});
return Json(gridData);
Instead of the above code please place the below code.
int totalRecords = gridData.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
var Data = new
{
total = totalPages,
page,
records = totalRecords,
rows = gridData
};
return Json(Data, JsonRequestBehavior.AllowGet);
I am using jqGrid V 4.6.0. and trying to implement grid with inline edit/delete functionality.I used formatter:'actions' for acheive this and also getting edit/delete icons in each row.But when i click on those icons i am getting following error in console :Uncaught TypeError: Cannot read property 'rowactions' of undefined and nothing happens in grid.same code and same example i've implemented before with jqGrid V4.4.4 and it worked well ,but in V4.6.0 i got this error.Please somebody help me.Thanks in advance :)
Code for reference:
jQuery("#theGrid").jqGrid({
url: '/Student/Grid',
datatype: "json",
colNames: ['Id', 'Firstname', 'Middlename', 'Lastname', 'Birthdate', 'Birthplace', 'State', 'Nationality', 'Religion', 'Ishandicaped ?', 'Actions'],
colModel: [
{ key: true, name: 'Id', sortable: true, resize: true, align: "center" },
{ key: false, name: 'FirstName', index: 'FirstName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'MiddleName', index: 'MiddleName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'LastName', index: 'LastName', editable: true, align: "center", editrules: { required: true } },
{
key: false, name: 'Birthdate', index: 'Birthdate', editable: true, align: "center", editrules: { required: true }, formatter: 'date', editoptions: {
dataInit: function (el) {
setTimeout(function () {
$(el).datepicker({
dateFormat: "dd-M-yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
}, 200);
}
}
},
{ key: false, name: 'Birthplace', index: 'Birthplace', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'State', index: 'State', editable: true, align: "center", edittype: "select", editoptions: { value: "GJ:Gujarat;MH:Maharashtra;DL:Delhi;BNG:Banglore;RJ:Rajasthan" }, editrules: { required: true } },
{ key: false, name: 'Nationality', index: 'Nationality', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'Religion', index: 'Religion', editable: true, align: "center", editrules: { required: true } },
{
key: false, name: 'IsHandicaped', index: 'IsHandicaped', editable: true, align: "center", edittype: "checkbox", editoptions: { value: "True:False" }, formatter: Demo1
},
{
key: false,
name: 'Actions',
index: 'tax',
width: 80,
align: "center",
formatter: 'actions',
formatoptions: {
delOptions: { url: '/Student/Delete' }
}
}
],
rowNum: 10,
rownumbers: true,
autowidth: true,
rowList: [5, 10, 20],
pager: '#gridPager',
viewrecords: true,
sortorder: "desc",
reloadAfterSubmit: true,
altclass: 'table table-bordered table-striped',
jsonReader: {
repeatitems: false
},
caption:'Studentdata JqGrid V4.4.4',
editurl: '/Student/Edit',
mtype: "post",
height: '100%',
hiddengrid: false,
serializeRowData: function (postData) {
debugger;
// new row id is "new_row"
postData.Id == "jqg1" ? postData.oper = "add" : postData.oper = "add";
return postData;
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [true, ''];
} else {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [false, response.responseText];
}
}
}
});
I have now a problem with validation of a record that is being edited.
The edit form (and the add form) has a field called "email". That field should be unique in database, so I use ajax to validate it, by mean of this function:
function check_email(value, colname) {
$.ajax({
url: '#Url.Action("CheckEmail")',
data: { email: value },
type: 'POST',
async: false,
datatype: 'text',
success: function (data) {
if (!data) result = [true, ""];
else result = [false, colname + ": ya existe en el sistema"];
}
})
return result;
}
This works, but the problem is when I am editing the record. Of course e-mail exists in this case, so it is not allowing me to save the record.
The algorithm might be: it should validate only if id is > 0 and the entered e-mail is different from the existing value. In other words, validation must occur if the user is changing e-mail.
I spent a lot of time trying to figure out how to know if the editform is for adding or for editing, and even more, I was trying to find the value of the primary key of the record being edited, without any success.
Any help will be appreciated,
EDIT:
This is the code of the grid:
$("#personal").jqGrid({
url: "#Url.Action("List")",
datatype: "json",
mtype: "GET",
colNames: ["Departamento",
"Nombres",
"Apellido Paterno",
"Apellido Materno",
"RUT",
"Contraseña",
"Fecha Nacimiento",
"Fotografía",
"Estado Civil",
"Género",
"Dirección",
"Cargo",
"E-mail",
"Fecha Ingreso",
"Creación",
"Modificación"],
colModel: [
{ name: "dep_id", index: "dep_nombre", editable: true, edittype: "select", formatter: 'select', editoptions: { width: 100, value: "#ViewData["Departamentos"]" }, width: 250, editrules: { required: true }, formoptions: { elmsuffix: '<span class="required">*</span>' }, stype: 'select', searchoptions: { sopt: ['eq'], value: "#ViewData["Departamentos"]" } },
{ name: "per_nombres", index: "per_nombres", editable: true, width: 250, editoptions: { maxlength: 80, size: 32 }, editrules: { required: true }, formoptions: { elmsuffix: '<span class="required">*</span>' } },
{ name: "per_apellido_paterno", index: "per_apellido_paterno", editable: true, width: 250, editoptions: { maxlength: 80, size: 32 }, editrules: { required: true }, formoptions: { elmsuffix: '<span class="required">*</span>' } },
{ name: "per_apellido_materno", index: "per_apellido_materno", editable: true, width: 250, editoptions: { maxlength: 80, size: 32 } },
{ name: "per_dni", index: "per_dni", editable: true, width: 100, editoptions: { maxlength: 20, size: 17, dataInit: function (el) { $.mask.definitions['~'] = '[0-9kK]'; $(el).mask("?99.999.999-~"); } }, editrules: { required: true, custom: true, custom_func: is_rut }, formoptions: { elmsuffix: '<span class="required">*</span>' }, searchoptions: { dataInit: function (el) { $.mask.definitions['~'] = '[0-9kK]'; $(el).mask("?99.999.999-~"); } } },
{ name: "per_contrasena", editable: true, edittype: "password", hidden: true, width: 100, editoptions: { maxlength: 50, size: 17 }, editrules: { required: false, edithidden: true } },
{ name: "per_fecha_nacimiento", index: "per_fecha_nacimiento", editable: true, width: 100, editrules: { date: true, required: false }, formatter: 'date', formatoptions: { srcformat: 'SortableDateTime', newformat: 'd-m-Y' }, editoptions: { size: 17, dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } }, searchoptions: { dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } } },
{ name: "per_fotografia", index: "per_fotografia", editable: true, width: 250, edittype: "file", editoptions: { maxlength: 255, size: 32 } },
{ name: "per_estado_civil", index: "per_estado_civil", editable: true, edittype: "select", editoptions: { value: ":;S:Soltero;C:Casado;V:Viudo;D:Divorciado" }, width: 100, stype: 'select', searchoptions: { sopt: ['eq'], value: ":;S:Soltero;C:Casado;V:Viudo;D:Divorciado" } },
{ name: "per_sexo", index: "per_sexo", editable: true, edittype: "select", editoptions: { value: ":;M:Masculino;F:Femenino" }, width: 100, stype: 'select', searchoptions: { sopt: ['eq'], value: ":;M:Masculino;F:Femenino" } },
{ name: "per_direccion", index: "per_direccion", editable: true, width: 250, editoptions: { maxlength: 512, size: 32 } },
{ name: "per_cargo", index: "per_cargo", editable: true, width: 100, editoptions: { maxlength: 50, size: 32 } },
{ name: "per_email", index: "per_email", editable: true, width: 100, editoptions: { maxlength: 80, size: 32 }, editrules: { email: true, required: false, custom: true, custom_func: check_email } },
{ name: "per_fecha_ingreso", index: "per_fecha_ingreso", editable: true, width: 100, editrules: { date: true, required: false }, formatter: 'date', formatoptions: { srcformat: 'SortableDateTime', newformat: 'd-m-Y' }, editoptions: { size: 17, dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } }, searchoptions: { dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } } },
{ name: "per_creado_el", index: "per_creado_el", editable:false, search:false, width: 100, align: "center", formatter: "date" },
{ name: "per_modificado_el", index: "per_modificado_el", editable:false, search:false, width: 100, align: "center", formatter: "date" },
],
jsonReader: {
repeatitems: false,
id: "per_id"
},
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
sortname: "per_apellido_paterno",
sortorder: "asc",
viewrecords: true,
gridview: true,
autoencode: true,
multiselect: true,
shrinkToFit: false,
caption: "Funcionarios",
editurl: "#Url.Action("AjaxEdit")",
height: '100%',
width: 935,
rownumbers: true,
rownumWidth: 40
});
$("#personal").jqGrid('hideCol', ["per_fotografia", "per_direccion"]);
$("#personal").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true, search: false }, { width: 500 }, { width: 500 }, {}, { multipleSearch: false, multipleGroup: false });
$("#personal").jqGrid('filterToolbar', { searchOperators: false });
$.jgrid.edit.addCaption = "Agregar Funcionario";
$.jgrid.edit.editCaption = "Modificar Funcionario";
$.jgrid.edit.saveData = "¡El funcionario fue modificado! ¿Almacena los cambios?";
$.jgrid.formatter.date.newformat = 'd-m-Y H:i';
Thanks
Jaime
I think you should send the record ID for verification.
function check_email(value, colname) {
var rowid = jQuery('#personal').jqGrid('getGridParam', 'selrow');
$.ajax({
url: '#Url.Action("CheckEmail")',
data: { email: value, rowid: rowid },
type: 'POST',
async: false,
datatype: 'text',
success: function (data) {
if (!data) result = [true, ""];
else result = [false, colname + ": ya existe en el sistema"];
}
})
return result;
}
and so the server has any record can be checked with the ID does not match with the rowid.
I'm trying to load the subgrid data from the main grid. The main grid loads fine but When I click on a row the subgrid data does not load.
Don't know what I'm missing. Please help.
Below is the code I'm using.
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
var mydata = [],
grid = $("#list");
var mainGridPrefix = "s_";
grid.jqGrid({
url: '${recordsUrl}',
datatype: 'json',
ignoreCase: true,
mtype: 'GET',
colNames: ['Global Search', 'serverId', 'DeviceName', 'Description', 'Console', 'OS', 'Business Unit', 'Model', 'Manufacturer', 'Serial Number', 'LifeCycle', 'Tier'],
colModel: [{
name: 'globalSearch',
index: 'globalSearch',
width: 50,
hidden: true,
searchoptions: {
searchhidden: true
}
}, {
name: 'serverId',
index: 'serverId',
width: 10,
hidden: true
}, {
name: 'deviceName',
index: 'deviceName',
width: 50
}, {
name: 'serverDesc',
index: 'serverDesc',
width: 70
}, {
name: 'console',
index: 'console',
width: 50
}, {
name: 'groupName',
index: 'groupName',
width: 40
}, {
name: 'businessUnit',
index: 'businessUnit',
width: 30
}, {
name: 'model',
index: 'model',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'manufacturer',
index: 'manufacturer',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'serialNumber',
index: 'serialNumber',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'lifeCycle',
index: 'lifeCycle',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'tier',
index: 'tier',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}],
postData: {},
rowNum: 10,
rowList: [10, 20, 40, 60],
height: 'auto',
autowidth: true,
rownumbers: true,
pager: '#pager',
sortname: 'deviceName',
viewrecords: true,
sortorder: "asc",
caption: "Records",
emptyrecords: "Empty records",
idPrefix: mainGridPrefix,
loadonce: true,
loadComplete: function () {},
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "cell",
id: "serverId"
},
subGrid: true,
beforeProcessing: function (data) {
var rows = data.rows,
l = rows.length,
i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.apps) {
subgrids[item.id] = item.apps;
}
}
data.userdata = subgrids;
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId),
subgrids = $(this).jqGrid("getGridParam", "userData");
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid({
datatype: "local",
data: subgrids[pureRowId],
colNames: ["App Id", "Desc"],
colModel: [{
name: "appId"
}, {
name: "applicationDesc"
}],
sortname: "applicationDesc",
height: "100%",
rowNum: 10000,
autoencode: true,
autowidth: true,
jsonReader: {
repeatitems: false,
id: "appId"
},
gridview: true,
idPrefix: rowId + "_"
});
}
});
$("#search").click(function () {
var searchFiler = $("#filter").val(),
f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, {
filters: ""
});
}
f = {
groupOp: "OR",
rules: []
};
f.rules.push({
field: "globalSearch",
op: "cn",
data: searchFiler
});
f.rules.push({
field: "deviceName",
op: "cn",
data: searchFiler
});
grid[0].p.search = true;
$.extend(grid[0].p.postData, {
filters: JSON.stringify(f)
});
grid.trigger("reloadGrid", [{
page: 1,
current: true
}]);
});
grid.jqGrid('navGrid', '#pager', {
edit: false,
add: false,
del: false,
search: true,
view: true
}, {}, {}, {}, { // search
sopt: ['cn', 'eq', 'ne', 'lt', 'gt', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}, { // vew options
beforeShowForm: function (form) {
$("tr#trv_id", form[0]).show();
},
afterclickPgButtons: function (whichbutton, form, rowid) {
$("tr#trv_id", form[0]).show();
}
});
grid.navButtonAdd('#pager', {
caption: "Add",
buttonicon: "ui-icon-plus",
onClickButton: addRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Edit",
buttonicon: "ui-icon-pencil",
onClickButton: editRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Delete",
buttonicon: "ui-icon-trash",
onClickButton: deleteRow,
position: "last",
title: "",
cursor: "pointer"
});
});
//]]>
you forgot to add the index: information for the colModel in the subgrid, you also need to pay attention to capitalization if the name is capitalized then so should be the index, that way jqgrid knows that where it needs to put the data. Here is the fixed code and also a link to a working example
//<![CDATA[
$(document).ready(function () {
var mydata = [{
globalsearch: "1",
serverId: "Test Name1",
deviceName: "Test Address1",
Console: "Test Date1"
}, {
globalsearch: "2",
serverId: "Test Name2",
deviceName: "Test Address2",
Console: "Test Date2"
}, {
globalsearch: "3",
serverId: "blah",
deviceName: "hello",
Console: "basketball"
}];
grid = $("#list");
var mydata2 = [{
AppId: "1",
Desc: "Test Name1"
}, {
AppId: "2",
Desc: "Test Name2"
}, {
AppId: "3",
Desc: "blah"
}];
var mainGridPrefix = "s_";
grid.jqGrid({
datatype: 'local',
data: mydata,
colNames: ['globalsearch', 'serverId', 'deviceName', 'Description', 'Console', 'OS', 'Business Unit', 'Model', 'Manufacturer', 'Serial Number', 'LifeCycle', 'Tier'],
colModel: [{
name: 'globalsearch',
index: 'globalsearch',
width: 50,
}, {
name: 'serverId',
index: 'serverId',
width: 10,
hidden: false
}, {
name: 'deviceName',
index: 'deviceName',
width: 50
}, {
name: 'serverDesc',
index: 'serverDesc',
width: 70
}, {
name: 'Console',
index: 'Console',
width: 50
}, {
name: 'groupName',
index: 'groupName',
width: 40
}, {
name: 'businessUnit',
index: 'businessUnit',
width: 30
}, {
name: 'model',
index: 'model',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'manufacturer',
index: 'manufacturer',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'serialNumber',
index: 'serialNumber',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'lifeCycle',
index: 'lifeCycle',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'tier',
index: 'tier',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}],
rowNum: 10,
rowList: [10, 20, 40, 60],
rownumbers: true,
pager: '#pager',
sortname: 'deviceName',
viewrecords: true,
sortorder: "asc",
caption: "Records",
height: 'auto',
autowidth: true,
loadComplete: function () {},
subGrid: true,
beforeProcessing: function (data) {
var rows = data.rows,
l = rows.length,
i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.apps) {
subgrids[item.id] = item.apps;
}
}
data.userdata = subgrids;
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId),
subgrids = $(this).jqGrid("getGridParam", "userData");
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid({
datatype: "local",
data: mydata2,
colNames: ["AppId", "Desc"],
colModel: [{
name: "AppId",
index: "AppId"
}, {
name: "Desc",
index: "Desc"
}],
sortname: "applicationDesc",
height: "100%",
rowNum: 10000,
autoencode: true,
autowidth: true,
jsonReader: {
repeatitems: false,
id: "appId"
},
gridview: true,
idPrefix: rowId + "_"
});
}
});
$("#search").click(function () {
var searchFiler = $("#filter").val(),
f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, {
filters: ""
});
}
f = {
groupOp: "OR",
rules: []
};
f.rules.push({
field: "globalSearch",
op: "cn",
data: searchFiler
});
f.rules.push({
field: "deviceName",
op: "cn",
data: searchFiler
});
grid[0].p.search = true;
$.extend(grid[0].p.postData, {
filters: JSON.stringify(f)
});
grid.trigger("reloadGrid", [{
page: 1,
current: true
}]);
});
grid.jqGrid('navGrid', '#pager', {
edit: false,
add: false,
del: false,
search: true,
view: true
}, {}, {}, {}, { // search
sopt: ['cn', 'eq', 'ne', 'lt', 'gt', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}, { // vew options
beforeShowForm: function (form) {
$("tr#trv_id", form[0]).show();
},
afterclickPgButtons: function (whichbutton, form, rowid) {
$("tr#trv_id", form[0]).show();
}
});
grid.navButtonAdd('#pager', {
caption: "Add",
buttonicon: "ui-icon-plus",
onClickButton: addRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Edit",
buttonicon: "ui-icon-pencil",
onClickButton: editRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Delete",
buttonicon: "ui-icon-trash",
onClickButton: deleteRow,
position: "last",
title: "",
cursor: "pointer"
});
});
//]]>
<table id="list"></table>
<div id="pager"></div>
Suppose the following grids
$(document).ready(function() {
$('#Clientes').jqGrid({colNames: ['Razón Social','Cuit','Dirección','Localidad','Teléfono','Tipo IVA','Mail','Saldo inicial','Facturar'],
colModel: [{ editable: true, editoptions: { "maxlength":70 }, editrules: { required: true }, name: 'RazonSocial' },
{ editable: true, editoptions: { dataInit: CuitMask, "maxlength":13 }, editrules: { custom: true, custom_func: ValidateCuit, required: true }, name: 'NidentFiscal' },
{ editable: true, editoptions: { "maxlength":70 }, editrules: { required: true }, name: 'Direccion' },
{ editable: true, edittype: 'select', editoptions: { dataUrl: '/Ciudad/CmbCiudad' }, editrules: { required: true }, name: 'Ciudad' },
{ editable: true, editoptions: { "maxlength":20 }, name: 'Telefono' }],
url: '/Clientes/List',
datatype: 'json',
mtype: 'POST',
pager: '#ClientesPager',
prmNames: { id: 'ClienteId' },
rowList: [10,15,20,25,30],
sortname: 'ClienteId',
subGrid: true,
subGridRowExpanded: function(subgridId, rowId) {
var subgridTableId = subgridId + '_t';
jQuery('#' + subgridId).append('<table id="' + subgridTableId + '"></table>');
var subgridPagerId = subgridId + '_p';
jQuery('#' + subgridId).append('<div id="' + subgridPagerId + '"></div>');
$('#' + subgridTableId).jqGrid({colNames: ['Fecha','Importe'],
colModel: [{ name: 'Fecha' },
{ editable: true, editrules: { number: true }, formatter: 'currency', formatoptions: { prefix: '$' }, name: 'Importe' }
],url: '/Honorarios/DetailSubgrid?id=' + rowId, datatype: 'json', mtype: 'POST', pager: '#' + subgridPagerId,
prmNames: { id: 'HonorarioId' },
rowList: [10,15,20,25,30],
sortname: 'HonorarioId',
viewrecords: true,
width: 600,
height: '100%'}).jqGrid('navGrid', '#' + subgridPagerId,{ search: false },{ url: '/Honorarios/Update', closeAfterEdit: true },{ url: '/Honorarios/Update', closeAfterEdit: true },{ url: '/Honorarios/Delete' });
},
viewrecords: true,
width: 1000,
height: '100%'
}).jqGrid('navGrid', '#ClientesPager',{ search: false },{ url: '/Clientes/Update', width: 500, closeAfterEdit: true }, { url: '/Clientes/Update', width: 500, closeAfterEdit: true }, { url: '/Clientes/Delete' });
});
I need to pass the ClienteId parameter when a record is added or edited in the sub grid
This should be done using postdata?
something like
postData: {ClienteId: row_id}
the solution is using
editData: { ClienteId: rowId }
Tanks #tpeczek