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.
Related
How can I do to add value in jqgrid and save it later in the database via an external button that I created in my page out of jqgrid?
I have the following jqgrid:
<script type="text/javascript">
...
jQuery(#grid-table).jqGrid({
url: '#Url.Action("GetStore", "Store")',
datatype: 'json',
mtype: 'Get',
height: '430',
colNames: [ 'Code', 'Name' ],
colModel: [
{ key: true, name: 'Id', index: 'Id', sorttype: "int" },
{ key: false, name: 'Name', index: 'Name', editable: true }
],
viewrecords: true,
loadonce: true,
rowNum: 10,
rowList: [5, 10, 15],
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false
Id: "0"
},
pager: jQuery(#grid-pager),
altRows: true,
multiselect: true,
multiboxonly: true,
caption: "Stores",
});
jQuery(grid_selector).jqGrid('navGrid', #grid-pager,
{ //navbar options
edit: false,
add: true,
del: false,
search: false,
refresh: false,
view: false,
},
{
recreateForm: true,
url: '#Url.Action("Edit","Store")',
},
{
recreateForm: true,
url: '#Url.Action("Create","Store")',
},
{
recreateForm: true,
url: '#Url.Action("Delete", "Store")',
},
{
recreateForm: true,
multipleSearch: true
},
{
recreateForm: true,
}
)
</script>
....
<button type="submit" class="btn btn-info" id="subitbutton">
Create
</button>
And the following code in my Model:
[Key]
public int Id { get; set; }
public string Name { get; set; }
And the following code in my Controller:
public JsonResult GetStores(string sidx, string sord, int page, int rows, int idStore)
{
int pageIndex = page - 1;
int pageSize = rows;
var storesResults = db.Stores.Select(
a => new { a.Id, a.Name });
int totalRecords = storesResults.Count();
var totalPages = (int) Math.Ceiling((float) totalRecords / (float) rows);
if (sord.ToUpper() == "ASC")
{
storesResults = storesResults.OrderBy(s => s.Name);
storesResults = storesResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
storesResults = storesResults.OrderByDescending(s => s.Name);
storesResults = storesResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages, page, records = totalRecords, rows = storesResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Create(Stores store)
{
db.Store.Add(store);
return view(store);
}
public ActionResult Edit(Store store)
{
if (ModelState.isValid)
{
db.Entry(store).State = EntityState.Modified;
db.SaveChanges();
}
return View(store);
}
public void Delete(string id)
{
var ids = id.Split(',');
foreach (var idStore in ids)
{
int storeId = Convert.ToInt32(idStore);
Store storeToDelete = db.Stores.Find(storeId);
db.Stores.Remove(storeToDelete);
}
db.SaveChanges();
}
Right now, my jqgrid sends each new row to the server and my method saves it in the database.
What I need is to store all rows in my view and send all at once in a single step to my server - using an external button, maybe?
Thanks in advance.
UPDATE
As requested by Oleg, here is my jqGrid demo:
<script type="text/javascript">
jQuery(function ($) {
var grid_selector = "#grid-table-dados-adicionais";
var pager_selector = "#grid-pager-dados-adicionais";
//resize to fit page size
$(window).on('resize.jqGrid', function () {
$(grid_selector).jqGrid('setGridWidth', $(".page-content").width());
})
//resize on sidebar collapse/expand
var parent_column = $(grid_selector).closest('[class*="col-"]');
$(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
//setTimeout is for webkit only to give time for DOM changes and then redraw!!!
setTimeout(function () {
$(grid_selector).jqGrid('setGridWidth', parent_column.width());
}, 0);
}
})
jQuery(grid_selector).jqGrid({
//direction: "rtl",
url: '#Url.Action("GetDadosAdicionais", "LojaDadosAdicionais", new { idLoja = #Model.Id })',
datatype: 'json',
mtype: 'Get',
height: '430',
colNames: [' ',
'Id',
'Name'
],
colModel: [
{
name: 'myac', index: '', width: 65, fixed: true, sortable: false, resize: false,
formatter: 'actions',
formatoptions: {
keys: true,
delOptions: {
recreateForm: true,
reloadAfterSubmit: false,
beforeShowForm: beforeDeleteCallback
},
editformbutton: true,
editOptions:
{
recreateForm: true,
reloadAfterSubmit: false,
closeAfterEdit: true,
beforeShowForm: beforeEditCallback,
closeOnEscape: true
}
}
},
{ key: true, hidden: true, name: 'Id', index: 'Id', sorttype: "int", editable: false },
{ key: false, hidden: true, name: 'Name', index: 'Name', sorttype: "int", editable: true },
],
viewrecords: true,
loadonce: true,
editurl: "clientArray",
rowNum: 10,
rowList: [5, 10, 15],
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
pager: jQuery(pager_selector),
altRows: true,
//toppager: true,
autowidth: true,
multiselect: true,
sortorder: "desc",
scrollOffset: 0,
height: "auto",
//multikey: "ctrlKey",
multiboxonly: true,
loadComplete: function () {
var table = this;
setTimeout(function () {
updateActionIcons(table);
updatePagerIcons(table);
enableTooltips(table);
}, 0);
},
caption: "Registration",
});
$(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size
//switch element when editing inline
function aceSwitch(cellvalue, options, cell) {
setTimeout(function () {
$(cell).find('input[type=checkbox]')
.addClass('ace ace-switch ace-switch-5')
.after('<span class="lbl"></span>');
}, 0);
}
//navButtons
jQuery(grid_selector).jqGrid('navGrid', pager_selector,
{ //navbar options
edit: true,
editicon: 'ace-icon fa fa-pencil blue',
add: true,
addicon: 'ace-icon fa fa-plus-circle purple',
del: true,
delicon: 'ace-icon fa fa-trash-o red',
search: true,
searchicon: 'ace-icon fa fa-search orange',
refresh: true,
refreshicon: 'ace-icon fa fa-refresh green',
view: true,
viewicon: 'ace-icon fa fa-search-plus grey',
},
{
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
reloadAfterSubmit: false,
width: 500,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
style_edit_form(form);
}
},
{
closeOnEscape: true,
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: false,
width: 500,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
.wrapInner('<div class="widget-header" />')
style_edit_form(form);
}
},
{
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
reloadAfterSubmit: false,
beforeShowForm: function (e) {
var form = $(e[0]);
if (form.data('styled')) return false;
form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
style_delete_form(form);
form.data('styled', true);
}
},
{
//search form
recreateForm: true,
reloadAfterSubmit: false,
afterShowSearch: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
style_search_form(form);
},
afterRedraw: function () {
style_search_filters($(this));
},
closeOnEscape: true,
closeAfterSearch: true,
multipleSearch: true
},
{
//view record form
recreateForm: true,
reloadAfterSubmit: false,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
}
}
)
$.extend($.jgrid.edit, {
beforeSubmit: function () {
$(this).jqGrid("setGridParam", { datatype: "json" });
return [true, "", ""];
}
});
$.extend($.jgrid.add, {
beforeSubmit: function () {
$(this).jqGrid("setGridParam", { datatype: "json" });
return [true, "", ""];
}
});
$('#filterButton').click(function (event) {
event.preventDefault();
filterGrid();
});
$('#TargetDate').datepicker({
dateFormat: 'mm/dd/yy'
});
function filterGrid() {
var postDataValues = $("#grid").jqGrid('getGridParam', 'postData');
// grab all the filter ids and values and add to the post object
$('.filterItem').each(function (index, item) {
postDataValues[$(item).attr('id')] = $(item).val();
});
$('#grid').jqGrid().setGridParam({ postData: postDataValues, page: 1 }).trigger('reloadGrid');
}
function style_edit_form(form) {
//enable datepicker on "sdate" field and switches for "stock" field
form.find('input[name=sdate]').datepicker({ format: 'yyyy-mm-dd', autoclose: true })
form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
//update buttons classes
var buttons = form.next().find('.EditButton .fm-button');
buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')
buttons = form.next().find('.navButton a');
buttons.find('.ui-icon').hide();
buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');
}
function style_delete_form(form) {
var buttons = form.next().find('.EditButton .fm-button');
buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
}
function style_search_filters(form) {
form.find('.delete-rule').val('X');
form.find('.add-rule').addClass('btn btn-xs btn-primary');
form.find('.add-group').addClass('btn btn-xs btn-success');
form.find('.delete-group').addClass('btn btn-xs btn-danger');
}
function style_search_form(form) {
var dialog = form.closest('.ui-jqdialog');
var buttons = dialog.find('.EditTable')
buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
}
function beforeDeleteCallback(e) {
var form = $(e[0]);
if (form.data('styled')) return false;
form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
style_delete_form(form);
form.data('styled', true);
}
function beforeEditCallback(e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
style_edit_form(form);
}
//replace icons with FontAwesome icons like above
function updatePagerIcons(table) {
var replacement =
{
'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
};
$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
})
}
function updateActionIcons(table) {
var replacement =
{
'ui-ace-icon fa fa-pencil': 'ace-icon fa fa-pencil blue',
'ui-ace-icon fa fa-trash-o': 'ace-icon fa fa-trash-o red',
'ui-icon-disk': 'ace-icon fa fa-check green',
'ui-icon-cancel': 'ace-icon fa fa-times red'
};
$(table).find('.ui-pg-div span.ui-icon').each(function () {
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
})
}
function enableTooltips(table) {
$('.navtable .ui-pg-button').tooltip({ container: 'body' });
$(table).find('.ui-pg-div').tooltip({ container: 'body' });
}
//var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');
$(document).one('ajaxloadstart.page', function (e) {
$(grid_selector).jqGrid('GridUnload');
$('.ui-jqdialog').remove();
});
});
</script>
....
<button type="submit" class="btn btn-info" id="submitbutton">
Create
</button>
If I correctly understand you then you can use editurl: "clientArray" to make local editing. You use form editing. So you should use jqGrid 4.7 or better free jqGrid 4.8 (or the latest version from github).
$("#subitbutton").click(function () {
var localGridData = $("#grid-table").jqGrid("getGridParam", "data");
$.ajax({
url: "someServerMethod",
type: "POST",
data: JSON.stringify(localGridData),
dataType: "json"
})
});
Depend on the implementation on the server side the format of the value of the data parameter can be different. You can probably use data: { gridData: localGridData } or some another option of jQuery.ajax.
i am populating jquery flexigrid by returning records in json format from c# controller. however i am facing little bit problem. I am adding herf column to delete the particular record. it works fine but i cant find way to confirm it before deleting it. below is my c# code which returns records to flexigrid.
C# Controller Snippet
private JsonResult CreateFlexiJson(IEnumerable<user> items, int page, int total)
{
var CurentsessionUser = Session["sessionUserId"].ToString();
List<Object> rows = new List<Object>();
foreach (var item in items)
{
rows.Add(new
{
id = item.id,
cell = new string[] {
item.msisdn,
item.pin,
item.subtype,
CurentsessionUser =="csagent"?"":String.Format("Change Pin"),
CurentsessionUser =="csagent"?"":String.Format("Delete")
}
});
}
var result = new { page = page, total = total, rows = rows };
return Json(result);
}
public ActionResult Delete(string subno)
{
try
{
wmas_subsEntities entitymodel = new wmas_subsEntities();
var customer = from p in entitymodel.users where p.msisdn == subno select p;
if (customer.ToList().Count > 0)
{
entitymodel.users.Remove(customer.First());
entitymodel.SaveChanges();
}
//return Json("Successfully deleted the user registeration");
return View("Index");
}
catch (Exception ex)
{
throw ex;
}
}
View
$('#CustomerList').flexigrid({
dataType: 'json',
colModel: [
{
display: 'Subscriber No.',
name: 'msisdn',
width: 100,
sortable: true,
align: 'left'
},
{
display: 'Pin Code',
name: 'pin',
width: 100,
sortable: true,
align: 'left'
},
{
display: 'Postpaid/Prepaid',
name: 'subtype',
width: 100,
sortable: true,
align: 'left'
},
{
display: '',
name: '',
width: 100,
sortable: true,
align: 'left'
},
{
display: '',
name: '',
width: 100,
sortable: true,
align: 'left'
}
],
title: 'Customer',
useRp: true,
rp: 15,
width: 600,
height:400,
singleSelect: true
});
In CreateFlexiJson action, change below line
CurentsessionUser =="csagent"?"":String.Format("Delete")
TO
CurentsessionUser =="csagent"?"":String.Format("<a href='javascript:void(0)' onclick='deleteSubscriber(\"" + item.msisdn + "\")'>Delete</a>")
And add javascript function deleteSubscriber
function deleteSubscriber(subno) {
if (confirm("Are you sure to delete Subscriber (No. = " + subno + ")")) {
location.href = "Delete?subno=" + subno;
}
}
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.
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