Related
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.
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.
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 working on a MVC application. I have written a jqGrid in my aspx page.
$(document).ready(function () {
jQuery("#jqgajax").jqGrid({
url: 'http://localhost:54136/home/fetchData',
datatype: "json",
colNames: ['ProcessName', 'WorkingSet64'],
colModel: [
{ name: 'ProcessName', index: 'ProcessName', width: 55 },
{ name: 'WorkingSet64', index: 'WorkingSet64', width: 90 }
],
rowNum: 80,
mtype:'Get',
width: 700,
rowList: [10, 20, 30],
sortname:'id',
viewrecords: true,
sortorder: "desc",
caption: "New API Example"
});
});
C# Code at controller:
var jsonData = new
{
total =10,
page = 10,
records = 10,
rows = (
from p in pu
select new
{
id = ++counter,
cell = new
{
ProcessName = p.ProcessName.ToString(),
WorkingSet64 = p.Memory.ToString()
}
}).ToArray()
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
The issue it rows are getting generated in the grid, but there is no data in the rows.
Please let me know what am I doing wrong.
Default jsonReader wait for cell as array of strings. So you should replace the part of the code
cell = new
{
ProcessName = p.ProcessName.ToString(),
WorkingSet64 = p.Memory.ToString()
}
to
cell = new [] { p.ProcessName, p.Memory.ToString() }
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