how to use Content with MVC? - c#

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.

Related

jqGrid filter dropdownlist not working with special characters

When using jqGrid inbuilt functionality of column searching, the dropdwonlist refuses to display special characters such as ç, Ë etc. For some reason they get split into two rows. This means if we take a word "Dfëstuç" the dropdownlist or rather option list will be generated as such:
Dfë
undefined
stuç
undefined
My code is as follows:
#model WS.ViewModels.CaseViewModel
#{
ViewBag.Title = "";
Layout = "~/Views/Shared/_Layout.cshtml";
<meta charset="utf-8">
string idVendbanimiSelectValues = ":";
foreach (var item in Model.NomenklaturaVendbanimiDropDownListData.OrderBy(n => n.IdVendbanimi))
{
idVendbanimiSelectValues += ";" + item.IdVendbanimi + ":" + item.EnPershkrimi;
}
}
#section AdditionalCss {
#Styles.Render("~/Content/Styles/ui.jqgrid.min.css")
}
#section AdditionalJavaScript {
#Scripts.Render("~/bundles/jqgrid")
#Scripts.Render("~/Scripts/jqgrid-listsearch.js")
#Scripts.Render("~/Scripts/jquery.searchFilter.min.js")
<script type="text/javascript">
$(function () {
var idVendbanimiSelectValues = "#idVendbanimiSelectValues";
$('#list-grid').jqGrid({
url: '/Lenda/GridDataWithFilters/',
datatype: 'json',
mtype: 'GET',
colNames: ['CaseId','IdVendbanimi'],
colModel: [
{ name: 'CaseId', index: 'CaseId', align: 'right' },
{ name: 'IdVendbanimi', index: 'IdVendbanimi', align: 'left', stype: 'select', edittype: 'select', editoptions: { value: idVendbanimiSelectValues }, autoencode: false }
],
pager: $('#list-pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'CaseId',
sortorder: "asc",
viewrecords: true,
height: '100%',
width: '1200',
ignoreCase: true,
autoencode: true,
}).jqGrid('navGrid', '#list-pager', { edit: false, add: false, del: false, search: false, refresh: false });
$('#list-grid').jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, beforeSearch: function () {
// verify entered data before searching
var postData = $('#list-grid').jqGrid('getGridParam', 'postData');
var searchData = $.parseJSON(postData.filters);
var isThereValidationErrors = false;
var validationErrors = "";
for (var iRule = 0; iRule < searchData.rules.length; iRule++) {
var enteredValue = searchData.rules[iRule].data;
if (searchData.rules[iRule].field == "CaseId" && !isNumeric(enteredValue)) {
validationErrors += " Id Lenda must be a valid number.";
isThereValidationErrors = true;
}
}
if(isThereValidationErrors)
alert($.trim(validationErrors));
return isThereValidationErrors;
}
});
});
</script>
}
<h2>#ViewBag.Title</h2>
<br /><br />
<table id="list-grid"></table>
<div id="list-pager"></div>
Is your JSON data correctly UTF-8 encoded? e.g.:
the ë character should be encoded with two bytes, 0xC3 0xAB.
the JSON data maybe needs a UTF-8 preamble, 0xEF 0xBB 0xBF.

JqGrid 404 on get from controller

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.

Confirmation box to delete record jquery flexigrid c#

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

Send row_id of main jqgrid to add event of subgrid

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.

filtering jqgrid based on user input

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

Categories

Resources