everything is working fine with my jqgrid except a small issue. i have defined postData below:
$(document).ready(function() {
$("#ctl00_ContentPlaceHolder2_drpUSite").change(function() {
site = ($("#ctl00_ContentPlaceHolder2_drpUSite").val());
loadusergrid();
});
var usrparams = new Object();
var site = ($("#ctl00_ContentPlaceHolder2_drpUSite").val());
//----grid code---------
$("#users").jqGrid({
prmNames: {
_search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: { searchString: '', searchField: '', searchOper: '', sites: site },
datatype: function(postdata) {
mtype: "GET",
$.ajax({
url: 'Users.aspx/GetUsers',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function(data, st) {
if (st == "success") {
var grid = $("#users")[0];
var m = JSON.parse(data.d);
grid.addJSONData(m);
}
},
error: function() {
alert("Loading Failed!");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id: "login",
repeatitems: true
},
colNames: ['Login', 'First Name', 'Last Name', 'Email', 'Site', 'Role', 'Room', 'UnitID', 'Supervisor', 'Super'],
colModel: [
{ name: 'login', index: 'login', width: 20 },
{ name: 'fname', index: 'fname', width: 20, hidden: true },
{ name: 'lname', index: 'lname', width: 60, align: "center", sortable: true, searchoptions: { sopt: ['eq', 'ne']} },
{ name: 'email', index: 'email', width: 20, align: "center", sortable: false },
{ name: 'site', index: 'site', width: 50, align: "center", sortable: true, searchoptions: { sopt: ['eq', 'ne']} },
{ name: 'role', index: 'role', width: 15, align: "center", sortable: true, searchoptions: { sopt: ['eq', 'ne']} },
{ name: 'room', index: 'room', width: 30, align: "center", sortable: true },
{ name: 'unitid', index: 'unitid', width: 10, align: "center", sortable: false },
{ name: 'super', index: 'super', width: 20 },
{ name: 'supername', index: 'supername', width: 10, align: "center", sortable: false },
],
pager: "#pageusers",
viewrecords: true,
caption: "Registered Users",
imgpath: 'themes/steel/images',
rowNum: 20,
rowList: [10, 20, 30, 40, 50],
sortname: "pname",
sortorder: "desc",
showpage: true,
gridModel: true, gridToolbar: true,
onSelectRow: function(id) {
var ret = jQuery("#users").getRowData(id);
accpara.id = ret.id;
accpara.pname = ret.pname;
accpara.pid = ret.pid;
accpara.bld = ret.bld;
accpara.cname = ret.cname;
accpara.amt = ret.amt;
accpara.status = ret.status;
accpara.notes = ret.notes;
accpara.lname = ret.lname;
}
});
jQuery("#users").navGrid('#pageusers', { view: false, del: false, add: false, edit: false },
{}, // default settings for edit
{}, // default settings for add
{}, // delete
{closeOnEscape: true, multipleSearch: true,
closeAfterSearch: true
}, // search options
{}
);
$("#users").setGridWidth(1300, true);
$("#users").setGridHeight(500, true);
jQuery("#users").jqGrid('filterToolbar');
//----grid code ends here
function loadusergrid() {
$("#users").setGridParam({ page: 1 }, { pgbuttons: true }, { pginput: true }, { postData: { "site": site} }).trigger("reloadGrid");
}
});
when page loads for the 1st time, this works..
now i have 4 drop-downs which filter users. i have written a function which reloads the grid when the dropdown is changed, but it isnt working.. what am i doing wrong here?? when i enable postback for the dropdowns, i get the filtered result. i want to avoid postbacks on my page :). right now i have added just the site dropdown as the filter. once this starts working ill add the remaining 3.
firebug shows the ajax call is fired successfully but with an empty sitename. please note that the site dropdown cntains an empty value when page is loaded for the 1st time.
thanks in advance
$("#mygrid").setPostData({parameters}); does the trick
Related
I am using Jqgrid for inline editing with asp.net and using a handler.ashx file for storing values from the grid. It is working perfectly fine in my VS but when i publish and run it on iis it trows error.
following is the code for jqgrid
$("#grid-table-Labor").jqGrid({
url: 'LaborApproval.aspx/GetLaborData', //asp function to get all data from data base to grid
data: "{}",
datatype: 'json',
mtype: 'POST',
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
colNames: [' ', 'Employee Code', 'Name', 'Contractor', 'DOJ', 'Police Verification', 'Gate Pass Valid Upto', 'Status', 'Remark'],
colModel: [
{
name: 'myac', index: 'myac', width: 80, fixed: true, sortable: false, resize: false, formatter: 'actions',
formatoptions: {
keys: true,
delbutton: false,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{ name: 'EMPCODE', index: 'EMPCODE', width: 108, key: true },
{ name: 'NAME', index: 'NAME', width: 140 },
{ name: 'CONTNAME', index: 'CONTNAME', width: 160 },
{ name: 'DOJ', index: 'DOJ', width: 70, formatter: 'date', formatoptions: { newformat: 'd-m-y' } },
{ name: 'POLICE_VRIFICATION', index: 'POLICE_VRIFICATION', width: 124 },
{ name: 'GatePassValidUpto', index: 'GatePassValidUpto', editable: true, sorttype: "date", unformat: pickDate },
{ name: 'Approve', index: 'Approve', width: 148, editable: true, edittype: "select", editoptions: { value: "True:Approve;False:Rejected" } },
{ name: 'REMARK', index: 'REMARK', width: 150, sortable: false, editable: true, edittype: "textarea", editoptions: { rows: "2", cols: "10" } }
],
pager: '#grid-pager-Labor',
altRows: true,
//cacheUrlData: true,
//toppager: true,
rowNum: 10,
scrollOffset: 0, // to remove offset of scroll bar for imporved gui
rowList: [10, 50, 100, 200, 300, 500, 800, 1000, 1500],
//onSelectRow: editRow,
viewrecords: true,
emptyrecords: "Nothing to display",
//multiselect: true,
//multiboxonly: false,
gridview: true,
loadComplete: function () {
var table = this;
setTimeout(function () {
//styleCheckbox(table);
//updateActionIcons(table);
updatePagerIcons(table);
enableTooltips(table);
}, 0);
},
jsonReader: {
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
root: function (obj) { return obj.d; },
repeatitems: false,
id: "0"
},
editurl: 'Handler/JQGridHandler.ashx',
caption: 'Labor List',
shrinkToFit: true,
height: 'auto',
//autowidth: true,
xmlReader: {
root: "list",
row: "Response",
id: "cfgId",
repeatitems: false
},
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex($(e.target).closest("td")[0]);
if (this.p.colModel[iCol].name === 'EMPCODE') {
var param = { param: rowid };
console.log(rowid);
$.ajax({
url: "LaborApproval.aspx/ShowMe",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
var box = bootbox.dialog({
show: true,
message: data['d'],
title: "Labour Details",
buttons: {
ok: {
label: "OK",
className: "btn-primary",
callback: function() {
console.log('OK Button');
}
}
}
});
box.modal('show');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message)
// console.log("Ajax Error!");
}
});
return false;
}
}
});
and following is the error
[HttpException]: The file '/CMS/Web_Pages/HR_Pages/Handler/JQGridHandler.ashx' does not exist.
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean ensureIsUpToDate)
at System.Web.UI.SimpleHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)
at System.Web.HttpApplication.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
i just had to put
editurl: '../../Handler/JQGridHandler.ashx',
before the link
C# MVC4
I am receiving an error of:
GET http://BLAHBLAHBLAH/Address/AddressData/ [HTTP/1.1 404 Not Found 71ms]
in the debugger.
My JS definition is as follows:
$(function () {
var filter = $("#ClientId").val();
//Address Grid
$("#tickets").jqGrid({
url: '/Address/AddressData/',
datatype: 'json',
mtype: 'GET',
postData: {
filters: filter
},
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true,
colNames: ['Action', 'AddressId', 'AddressLine1', 'AddressLine2', 'City', 'State', 'Zip', 'Available'],
colModel: [
{
name: 'Action',
width: 220,
align: 'center',
sortable: false,
search: false,
formatter: EditBtnFormatter,
},
{
name: 'Id',
index: 'Id',
width: 300,
align: 'left',
sortable: true,
search: true,
},
{
name: 'AddressLine1',
index: 'AddressLine1',
width: 800,
align: 'left',
sortable: true,
search: false,
},
{
name: 'AddressLine2',
index: 'AddressLine2',
width: 600,
align: 'left',
sortable: true,
search: false,
},
{
name: 'City',
index: 'City',
width: 350,
align: 'left',
sortable: true,
search: false,
},
{
name: 'State',
index: 'State',
width: 200,
align: 'left',
sortable: true,
search: false,
},
{
name: 'Zip',
index: 'Zip',
width: 250,
align: 'left',
sortable: true,
search: false,
},
{
name: 'Available',
index: 'Deleted',
width: 250,
align: 'left',
sortable: true,
search: false,
}
],
pager: jQuery('#pager'),
rowNum: 30,
rowList: [20, 30, 40, 50],
search: true,
sortname: 'AddressLine1',
sortorder: 'asc',
viewrecords: true,
gridview: true,
imgpath: 'content/themes/base/images',
caption: 'Addresses',
formatter: 'Action',
autowidth: true,
formatoptions: {
keys: true,
editformbutton: true
}
}).jqGrid('gridResize', null).navGrid('#pager', { view: false, del: false, add: false, edit: false },
{}, // default settings for edit
{}, // default settings for add
{}, // delete
{
closeOnEscape: true, multipleSearch: true, searchOnEnter: true,
closeAfterSearch: true
}, // search options
{}
);
jQuery("#addrs").setGridWidth(1200, true);
jQuery("#addrs").setGridHeight(600, true);
function EditBtnFormatter(cellvalue, options, rowObject) {
console.log(rowObject);
return (('<a title="Edit" href ="#Url.Action("Edit","Address")' + '/' + rowObject[1] + '"><img src="../../Content/themes/base/images/edit_icon_fer_checklist.png" /></a>'));
}
and my controller is
public JsonResult AddressData(string sidx, string sord, int page, int rows, bool _search, string filters)
{
var newfil = Int32.Parse(filters);
var pageSize = rows;
var totalRecords = (from addrs in db.Addresses where addrs.ClientId == newfil select addrs).Count();
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
string orderby = sidx + " " + sord;
if (sidx == "AddressLine1")
{
orderby = "AddressLine1" + " " + sord;
}
var addresses = (from addr in db.Addresses select addr).OrderBy(orderby);
if (_search)
{
addresses = addresses.Where(x => x.ClientId.Equals(newfil));
}
var addressData =
(from addrs in addresses
select new { addrs.Id, addrs.AddressLine1, addrs.AddressLine2, addrs.City, addrs.State, addrs.Zip, addrs.Deleted }).ToList
();
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from item in addressData
select new
{
cell = new[]
{
string.Empty,item.Id.ToString(), item.AddressLine1, item.AddressLine2, item.City, item.State, item.Zip, item.Deleted
}
}
)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
It works locally, but for some reason it will not populate the grid and I am getting the 404 error even though I know the link is valid. I hope someone can point out just a silly mistake I've overlooked.
When running localhost it typically puts the project name after localhost like this:
http://localhost/projectname/page
When running on a server, you lose the project name:
http://server/page
Make sure your path in jquery realizes that.
I have a Kendo Grid that uses Inline Editing. Instead of using the standard Edit() command that is available within the Kendo Framework, I would like to have a kendo Custom Command that when clicked it finds the current row and puts that row in edit mode.
This grid also appends a new row to the bottom of the grid.
Note: I am trying to simulate batch editing client side.
Please follow this example :
<body>
<h1>Kendo Grid</h1>
<hr />
<div id="Correspondence"></div>
<input type="hidden" id="hdnEmployeeId" />
<script>
//Parent grid
$(document).ready(function () {
var element = $("#Correspondence").kendoGrid({
dataSource: {
data: #Html.Raw(Json.Encode(Model)),
editable: { destroy: true },
batch: true,
pageSize: 5,
schema: {
model: {
id: "EmployeeId",
fields: {
EmployeeId: { type: "number" },
Name: { type: "string" },
Gender: { type: "string" },
City: { type: "string" }
}
}
}
},
height: 430,
sortable: true,
pageable: true,
selectable: true,
detailInit: detailInit,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns:
[
{ field: "EmployeeId", title: "EmployeeId", width: "110px" },
{ field: "Name", title: "Name", width: "110px" },
{ field: "Gender",title: "Gender", width: "110px" },
{ field: "City",title: "City", width: "110px" },
],
change: function () {
//Get the selected row id
alert("EmployeeId "+ this.dataItem(this.select()).EmployeeId);
}
});
//you can expand it programatically using the expandRow like this
element.on('click', 'tr', function () {
$(element).data().kendoGrid.expandRow($(this));
})
//Child grid
function detailInit(e) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
data: #Html.Raw(Json.Encode(Model)),
editable: { destroy: true },
batch: true,
pageSize: 5,
schema: {
model: {
id: "EmployeeId",
fields: {
EmployeeId: { type: "number" },
Name: { type: "string" },
Gender: { type: "string" },
City: { type: "string" }
}
}
}
},
scrollable: false,
sortable: false,
selectable: true,
pageable: true,
columns:
[
{ field: "EmployeeId", title: "EmployeeId", width: "110px" },
{ field: "Name", title: "Name", width: "110px" },
{ field: "Gender",title: "Gender", width: "110px" },
{ field: "City",title: "City", width: "110px" },
]
}).data("kendoGrid");
}
}); // end ready
</script>
</body>
public ActionResult GridSave(FormCollection data)
{
try
{
DataContext db = new DataContext();
int Id = int.Parse(data["Id"]);
var user = db.UserProfiles.Where(el => el.UserId == Id).FirstOrDefault();
if (user == null)
return Content("Record not found.");
if (data["FirstName"] != null)
user.FirstName = data["FirstName"];
if (data["LastName"] != null)
user.LastName = data["LastName"];
if (data["UserName"] != null)
{
var strUsername = data["UserName"];
var tempUser = db.UserProfiles.SingleOrDefault(x => x.UserName.Trim() == strUsername.Trim() && x.UserId != Id);
if (tempUser != null)
{
return Content("\"" + strUsername + "\" already in use.");
}
else
{
user.UserName = strUsername;
}
}
if (data["Password"] != null)
user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(data["Password"], "sha1");
if (data["PasswordExpiry"] != null)
user.Password_Expiry =Convert.ToString(data["PasswordExpiry"]);
user.Modified = Convert.ToString(DateTime.Now);
user.ModifiedBy = User.Identity.Name;
//db.UserProfiles.Add(user);
db.SaveChanges();
}
catch(Exception ex)
{
return Content("System Error: "+ex);
}
return Json(true);
}
i want to use this code in my project. but i don't know how to show error message using return Content() what should i do to show error message in jqgrid
this is my grid:
jQuery(document).ready(function () {
var grid = jQuery("#grid");
grid.jqGrid({
url: '/Admin/GetContactsForJQGrid',
datatype: 'json',
mtype: 'Post',
cellsubmit: 'remote',
cellurl: '/Admin/GridSave',
success:function(){alert(data)},
formatCell: emptyText,
colNames:['Id', '', 'First Name', 'Last Name', 'User Name', 'Password', 'Password Expiry', 'Last Modified', 'Last Modified By', 'Created By', ''],
//['Id', 'Privileges', 'FirstName', 'LastName', 'UserName', 'Password', 'Type', 'Password_Expiry', 'CreatedBy', 'Modified', 'ModifiedBy'],
colModel: [
{ name: 'Id', index: 'Id', width: "30", align: "left", key: true, hidden: true, editrules: { edithidden: true } },
{ name: 'Privileges', index: 'Privileges', width: 70, resizable: false, editable: false, align: 'center', formatter: formatLink, classes: 'not-editable-cell' },
{ name: 'FirstName', index: 'FirstName', align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'LastName', index: 'LastName', align: "left", sorttype: 'text', resizable: true, editable: true },
{ name: 'UserName', index: 'UserName', align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'Password', index: 'Password', align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'Type', width: "100", index: 'Type', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
{ name: 'Password_Expiry', index: 'Password_Expiry', align: "left", sorttype: 'date', resizable: true, editable: true, editrules: { required: true }, formatter: 'date', formatoptions: { srcformat: 'm/d/Y', newformat: 'm/d/Y' }, editoptions: { readonly: true, dataInit: function (el) { $(el).datepicker() } } },
{ name: 'CreatedBy', index: 'CreatedBy', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
{ name: 'Modified', index: 'Modified', sorttype: 'date', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
{ name: 'ModifiedBy', index: 'ModifiedBy', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' }
],
shrinkToFit: true,
//autowidth: true,
pager: '#pager',
height: '100%',
width: "703",
rowNum: 10,
rowList: [10, 20, 50, 100],
sortable: true,
loadonce: false,
ignoreCase: true,
viewrecords: true,
caption: 'Administration',
cellEdit: true,
hidegrid: false,
viewrecords: true,
gridComplete: function () {
var ids = grid.jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var isDeleted = grid.jqGrid('getCell', ids[i], 'Delete');
if (isDeleted == 'true') {
grid.jqGrid('setCell', ids[i], 'Delete', '<img src="/Images/delete.png" alt="Delete Row" />');
}
else {
grid.jqGrid('setCell', ids[i], 'Delete', ' ');
//grid.jqGrid('setCell', ids[i], 'Privileges', 'admin');
}
}
}
});
grid.jqGrid('navGrid', '#pager',
{ resize: false, add: false, del: false, search: true, refresh: false, edit: false, alerttext: 'Please select one user' }
).jqGrid('navButtonAdd', '#pager',
{ title: "Add New users", buttonicon: "ui-icon ui-icon-plus", onClickButton: showNewUsersModal, position: "First", caption: "" });
});
what should i do in html to show the error message. i have added this line success:function(){alert(data)},
but alert does't show.
when i edit the record in grid...request goes to cellurl: '/Admin/GridSave', and from there (in controller,action result) i am returning the error message by using return Content("System Error: "+ex); but i don't know how exactly use content in mvc 4 vs 12
any suggestion will be appreciable :)
It's not good to return just a text with Content("System Error: "+ex) from the method which return JSON too (see Json(true)). One can use return new EmptyResult(); for example instead of return Json(true);.
The code success:function(){alert(data)} will be ignored because jQuery supports callback success, but such callback is unknown for jqGrid. The list of callbacks supported by cell editing which you use you can find in the documentation. If you want return non-empty response in case of successful saving of data you can use afterSubmitCell or afterSaveCell callback.
For example afterSubmitCell can be used in the following way
afterSubmitCell: function (jqXHR) {
alert(jqXHR.responseText);
return [true]; // interpret the response as successful
}
jqGrid uses typically HTTP status code to detect whether the response of the server successful or not. The same do jQuery.ajax used by jqGrid internally. Some frameworks used on the server don't allow to set HTTP status code of the server response. In the case the callback afterSubmitCell is very helpful. One can analyse the server response and returns [true] in case of successful response and returns [false, "some error description"] in case of error. For example you can use some simple prefix like "!" in all error responses: return Content("!Record not found."); instead of return Content("Record not found.");, return Content("!\"" + strUsername + "\" already in use."); instead of return Content("\"" + strUsername + "\" already in use."); and so on. In the case you can use
afterSubmitCell: function (jqXHR) {
if (typeof jqXHR.responseText === string && jqXHR.responseText.charAt(0) === "!") {
return [false, jqXHR.responseText.substr(1)];
} else {
alert(jqXHR.responseText); // probably should be removed in the final version
return [true]; // interpret the response as successful
}
}
An alternative for usage of afterSubmitCell will be the usage of response having HTTP status code other as 200 (OK). For example you can use
public ActionResult GridSave (FormCollection data) {
try {
...
return new EmptyResult();
} catch (Exception ex) {
Response.StatusCode = 500;
Response.TrySkipIisCustomErrors = true;
return Content("System Error: " + ex.Message);
}
}
or more better:
public ActionResult GridSave (FormCollection data) {
try {
...
return new EmptyResult();
} catch (Exception ex) {
Response.StatusCode = 500;
Response.TrySkipIisCustomErrors = true;
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError,
"System Error: " + ex.Message);
}
}
In the case the callback afterSubmitCell will not be called in case of error. Instead of that you can use errorCell callback to display the error message. The corresponding code could be
errorCell: function (jqXHR) {
$.jgrid.info_dialog($.jgrid.errors.errcap,
jqXHR.status + " (" + jqXHR.statusText + "):<br/>" +
jqXHR.responseText,
$.jgrid.edit.bClose);
}
The above code uses $.jgrid.info_dialog instead of alert to display error message which more corresponds to jqGrid style. It's just an example of the usage. I wanted only to explain the possibilities which you have. The final code you should write yourself corresponds to exact reqirements of your project.
Be carefully with usage of the code which I included in my answer. I don't tested it, so some typing errors could exist.
Finally I would recommend you to use custom formatter instead of usage setCell in the loop inside of gridComplete. The current implementation is very slow in case of large number of rows. You should use gridview: true additionally to improve the performance.
I am using jqgrid 4.4's inlineNav functionality to provide Add/Edit capability for my subgrid. However I cannot figure out how to get the Add event to be called. Only the Update event is called when I "Add" the record.
I also don't know how to get the row_id from the parent grid row into the subgrid so that I can pass it to the Add event.
Here is my code
<script type="text/javascript">
$(document).ready(function () {
$('#jqgFactors').jqGrid({
//url from wich data should be requested
url: '#Url.Action("GetFactors")',
//type of data
datatype: 'json',
//url access method type
mtype: 'POST',
//columns names
colNames: ['id', 'category', 'question type', 'question', 'tooltip text', 'xdata', 'warningexception'],
//columns model
colModel: [
{ name: 'id', index: 'id', align: 'left', editable: false, width: '40px', fixed: true, key: true },
{ name: 'categoryid', index: 'categoryid', align: 'left', editable: true, edittype: 'select', width: '80px', fixed: true, editoptions: { value: { 1: 'Departure', 2: 'Pilot', 3: 'Product', 4: 'Flight', 5: 'Destination'} }, editrules: { required: true} },
{ name: 'type', index: 'type', align: 'left', editable: true, edittype: 'select', width: '100px', fixed: true, editoptions: { value: { 1: 'RadioButton List', 2: 'DatePicker'} }, editrules: { required: true} },
{ name: 'questiontext', index: 'questiontext', align: 'left', editable: true, edittype: 'textarea', width: '200px', fixed: true, editoptions: { rows: '5', cols: '40' }, editrules: { required: true} },
{ name: 'tooltip', index: 'tooltip', align: 'left', editable: true, edittype: 'textarea', width: '300px', fixed: true, editoptions: { rows: '5', cols: '40' }, editrules: { required: true} },
{ name: 'x', index: 'x', align: 'left', editable: true, edittype: 'select', width: '60px', fixed: true, editoptions: { value: { 1: 'true', 0: 'false'} }, editrules: { required: true} },
{ name: 'warningexception', index: 'warningexception', align: 'left', editable: true, edittype: 'select', width: '60px', editoptions: { value: { 1: 'true', 0: 'false'} }, editrules: { required: true} }
],
//pager for grid
pager: $('#jqgpFactors'),
rowNum: 60,
sortname: 'id',
sortorder: 'asc',
viewrecords: true,
height: '100%',
width: 900,
subGrid: true,
subGridRowExpanded: function (subgrid_id, row_id) {
var subgrid_table_id;
var subgrid_pager_id;
subgrid_table_id = subgrid_id + "_t";
subgrid_pager_id = "p_" + subgrid_table_id;
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + subgrid_pager_id + "' class='scroll'></div>");
$("#" + subgrid_table_id).jqGrid({
url: '#Url.Action("GetFactorDetails")',
postData: { QuestionId: function () { return row_id; } },
datatype: "json",
mtype: "POST",
colNames: ['id', 'questionid', 'text', 'influence', 'weight'],
colModel: [
{ name: "id", index: "id", key: true, hidden: true },
{ name: "questionid", index: "questionid", hidden: true },
{ name: "text", index: "text", width: 700, editable: true, edittype: 'text' },
{ name: "influence", index: "influence", width: 80, editable: true, edittype: 'text', editrules: { required: true, integer: true} },
{ name: "weight", index: "weight", sortable: false, width: 80, editable: true, edittype: 'text', editrules: { required: true, integer: true} }
],
height: '100%',
rowNum: 5,
sortname: 'id',
sortorder: 'asc',
pager: subgrid_pager_id,
editurl: 'clientArray',
width: 860
});
$("#" + subgrid_table_id).jqGrid('navGrid', '#' + subgrid_pager_id, { edit: false, add: false, del: false });
$("#" + subgrid_table_id).jqGrid('inlineNav', '#' + subgrid_pager_id, {
addParams: {
addRowParams: {
keys: true,
url: '#Url.Action("AddFactorDetail")'
}
},
editParams: {
url: '#Url.Action("UpdateFactorDetail")'
},
add: true,
edit: true,
save: true,
cancel: true
}
});
}
});
$.jgrid.nav.addtext = "Add Record";
$.jgrid.nav.edittext = "Edit Record";
$.jgrid.nav.deltext = "Delete Record";
$('#jqgFactors').jqGrid('navGrid', '#jqgpFactors',
{ add: true, del: true, edit: true, search: false },
{ width: 'auto', url: '#Url.Action("UpdateFactor")' },
{ width: 'auto', url: '#Url.Action("UpdateFactor")' }, //insert
{ width: 'auto', url: '#Url.Action("DeleteFactor")' });
$('#dlgFactor').dialog({ autoOpen: false, bgiframe: true, resizable: false, title: 'Factor' });
$('a[data-supplier-id]').live('click', function (e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
var dialogPosition = $(this).offset();
$.post('#Url.Action("Factor")', { FactorId: $(this).attr('data-supplier-id') }, function (data) {
$('#dlgFactor').empty();
$('#tmplFactor').tmpl(data).appendTo('#dlgFactor');
$('#dlgFactor').dialog('option', 'position', [dialogPosition.left, dialogPosition.top]);
$('#dlgFactor').dialog('open');
});
});
});
This is what I want the control to look like: Update is working fine.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateFactorDetail(FactorDetailModel model, int Id)
{
model.QuestionId = Id;
FactorManager fm = new FactorManager();
return Json(fm.UpdateDetail(model));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddFactorDetail(FactorDetailModel model, int QuestionId)
{
model.QuestionId = QuestionId;
FactorManager fm = new FactorManager();
return Json(fm.AddDetail(model));
}
Am not sure about your first question but to your second question, i think the following links will help you..
wiki-subgrid events-check example
Rick and Eric's answer - i assume you already know this as you have edited the post.
access parent grid id
Hope it helps.