This is the code I am using to load my jqGrid:
function getTopics() {
var fid = document.getElementById("SelectFunction").value;
//alert(fid);
$.ajax({
url: "Restful.svc/GetTopics",
data: { functionID: fid },
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data, status, xHR) {
var thegrid = jQuery("#editgrid")[0];
thegrid.addJSONData(JSON.parse(data.d));
$("#editgrid").fluidGrid({ example: "#outerContainer", offset: -10 });
},
error: function (xHR, status, err) {
alert("ERROR: " + status + ", " + err);
}
});
}
function LoadDataIntoGrid() {
var lastcell;
jQuery("#editgrid").jqGrid('GridUnload');
jQuery("#editgrid").jqGrid({
datatype: getTopics,
height: '300px',
colNames: ['TopicID', 'Topic', 'Description', 'Topic Entity', 'Inactive'],
colModel: [
{ name: 'TopicID', index: 'TopicID', width: 200, editable: false, editoptions: { readonly: true, size: 10} },
{ name: 'TopicCode', index: 'TopicCode', width: 100, editable: true, editoptions: { size: 10} },
{ name: 'TopicDescription', index: 'TopicDescription', width: 200, editable: true, editoptions: { size: 30} },
{ name: "TopicEntity", index: "TopicEntity", width: 200, editable: true, resizable: true, edittype: "select", editoptions: { value: returnEntityList()} },
{ name: 'Inactive', index: 'Inactive', width: 60, align: "center", editable: true, edittype: "checkbox", formatter: 'checkbox', formatoptions: { disabled: true} }
],
rowNum: 30,
rowList: [10, 20, 30],
pager: $('#pagernav'),
sortname: 'Topic',
viewrecords: true,
sortorder: "desc",
caption: "Topics",
editurl: "Restful.svc/SaveTopic",
onSelectRow: function (id) {
if (id && id !== lastcell) {
jQuery('#editgrid').jqGrid('restoreRow', lastcell);
jQuery('#editgrid').jqGrid('editRow', id, true);
lastcell = id;
}
}
}).navGrid('#pagernav', { edit: false, add: true, del: false });
}
Everything loads properly, and clicking on a row makes the fields editable like it should. When the enter key is pressed to save the edits the event seems to fire properly, and calls the "SaveTopic" method referenced in the editurl property. At this point I get an error.
If SaveTopic is defined like this:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
public void SaveTopic( string TopicCode, string TopicDescription, string TopicEntity, string Inactive, string oper, string id)
{
//Code Here
}
I get this error from jqGrid: "Error Row: 3 Result: 500:Internal Server Error Status: error"
If SaveTopic is defined like this(Method changed to GET):
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
public void SaveTopic( string TopicCode, string TopicDescription, string TopicEntity, string Inactive, string oper, string id)
{
//Code Here
}
I get this error from jqGrid: "Error Row: 3 Result: 405:Method Not Allowed Status: error"
I can't find anyone else having this problem, and according to the similar example I could find I seem to be doing it correctly. All help is greatly appreciated at this point.
WCF Services only allow HTTP Post requests: Hence they are not RESTFul otherwise they would pass data via the URL in a GET Request.
Your method says it accepts individual items ie a lot of strings. This is incorrect, automatic JSon binding isn't smart enough to bind each item separately. Try creating an information agent with the correct properties and receive that or a JSONResult object and parsing the data yourself. If you rely on automatic binding make sure to use the latest version of the .NET frame work either 3.5 SP1 or higher in which automatic JSon to Model binding is allowed.
Sources: Asp.net, Microsoft MVC 3.0 reference guide, msdn, trirand.com, ect.
I finally managed to to make it work using this work around. It isn't ideal, but it gets the job done. Code changes in bold.
function getTopics()
var fid = document.getElementById("SelectFunction").value;
//alert(fid);
$.ajax({
url: "Restful.svc/GetTopics",
data: { functionID: fid },
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data, status, xHR) {
var thegrid = jQuery("#editgrid")[0];
thegrid.addJSONData(JSON.parse(data.d));
$("#editgrid").fluidGrid({ example: "#outerContainer", offset: -10 });
},
error: function (xHR, status, err) {
alert("ERROR: " + status + ", " + err);
}
});
}
function LoadDataIntoGrid() {
var lastcell;
jQuery("#editgrid").jqGrid('GridUnload');
jQuery("#editgrid").jqGrid({
datatype: getTopics,
**ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },**
height: '300px',
colNames: ['TopicID', 'Topic', 'Description', 'Topic Entity', 'Inactive'],
colModel: [
{ name: 'TopicID', index: 'TopicID', width: 200, editable: false, editoptions: { readonly: true, size: 10} },
{ name: 'TopicCode', index: 'TopicCode', width: 100, editable: true, editoptions: { size: 10} },
{ name: 'TopicDescription', index: 'TopicDescription', width: 200, editable: true, editoptions: { size: 30} },
{ name: "TopicEntity", index: "TopicEntity", width: 200, editable: true, resizable: true, edittype: "select", editoptions: { value: returnEntityList()} },
{ name: 'Inactive', index: 'Inactive', width: 60, align: "center", editable: true, edittype: "checkbox", formatter: 'checkbox', formatoptions: { disabled: true} }
],
rowNum: 30,
rowList: [10, 20, 30],
pager: $('#pagernav'),
sortname: 'Topic',
viewrecords: true,
sortorder: "desc",
caption: "Topics",
editurl: "Restful.svc/SaveTopic",
onSelectRow: function (id) {
if (id && id !== lastcell) {
jQuery('#editgrid').jqGrid('restoreRow', lastcell);
jQuery('#editgrid').jqGrid('editRow', id, true);
lastcell = id;
}
}
}).navGrid('#pagernav', { edit: false, add: true, del: false });
}
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
public void SaveTopic() {
**int FunctionID = Convert.ToInt32(HttpContext.Current.Request.Form["FunctionID"]);
int TopicID = Convert.ToInt32(HttpContext.Current.Request.Form["TopicID"]);
string TopicCode = HttpContext.Current.Request.Form["TopicCode"];
string TopicDescription = HttpContext.Current.Request.Form["TopicDescription"];
int TopicEntity = Convert.ToInt32(HttpContext.Current.Request.Form["TopicEntity"]);
string Inactive = HttpContext.Current.Request.Form["Inactive"];
string oper = HttpContext.Current.Request.Form["oper"];
string id = HttpContext.Current.Request.Form["id"];**
//Code here
}
Related
I am having issues with Free Jqgrid where I can not get it to post to my developer version of Microsoft SQL server. I am using Microsoft visual studios. I am using entity framework 6 for the database connections. When I use break points it doesn't seem to hit my createbid, editbid, or delete bid. I also don't get any errors in console.
I have looked through and done many of the tutorials for editing updating and adding lines. I had the same problem. I cant find an answer that works on stack overflow through my research.
I published it to IIS to see if maybe it was something with visual studios and to see if anything changes but i did get some errors this time. It is not finding the /Home/GetBidValues, Home/EditBid, /Home/CreateBid, /Home/DeleteBid. this is weird because with visual studios it was at least getting data into the grid and showing it. So I will look into this further and see if there is something wrong with my ajax and also with my C# code.
Here is my Jquery file
$(function () {
$("#grid").jqGrid
({
url: "/Home/GetBidValues",
datatype: 'json',
mtype: 'Get',
colNames: ['Client Cost', 'ElementId', 'Note', 'Area', 'Element', 'Item', 'Qty', 'Description'], //Othr Misc
//colModel takes the data from controller and binds to grid
colModel: [
{
key: true,
hidden: true,
name: 'ElementId',
index: 'ElementId',
frozen: true,
editable: false
}, {
key: false,
name: 'Note',
index: 'Note',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Area',
index: 'Area',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Element',
index: 'Element',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
name: 'Item',
index: 'Item',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'QTY',
index: 'QTY',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Description',
index: 'Description',
frozen: true,
editable: true,
width: 70,
align: 'center'
}],
pager: '#pager',
gridview: true,
ignoreCase: true,
rowNumbers: false,
shrinkToFit: false,
height: '100%',
width: 1000,
viewrecords: true,
footerrow: true,
emptyrecords: 'No records to display',
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
}
});
$('#grid').jqGrid( 'inlineNav','#pager', {
edit: true,
add: true,
del: true,
cancel: true,
search: true,
refresh: true,
editparams: {
keys:true
}
}, {
// edit options
zIndex: 100,
url: '/Home/EditBid',
//datatype: 'json',
//mtype: 'Post',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},{//add
zIndex: 100,
url: "/Home/CreateBid",
closeOnEscape: true,
closeAfterAdd: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {
// delete options
zIndex: 100,
url: "/Home/DeleteBid",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
reloadaftersubmit: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
Here is my C# file
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ERPWebAppTest.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
namespace ERPWebAppTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
Test1Entities db = new Test1Entities();
[HttpGet]
public JsonResult GetBidValues(string sidx, string sord, int page, int rows)
{
//old code
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var Results = db.BidDetails.Select(
a => new
{
a.ElementID,
a.Note ,
a.Area ,
a.Element ,
a.Item ,
a.QTY ,
a.Descr ,
});
int totalRecords = Results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
Results = Results.OrderByDescending(s => s.ElementID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
Results = Results.OrderBy(s => s.ElementID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public string CreateBid([Bind(Exclude = "ElementID")] BidDetail obj)
{
Test1Entities db = new Test1Entities();
string msg;
try
{
if (ModelState.IsValid)
{
db.BidDetails.Add(obj);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfully";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
[HttpPost]
public string EditBid(BidDetail obj)
{
Test1Entities db = new Test1Entities();
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(obj).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
[HttpPost]
public string DeleteBid(int ElementID)
{
Test1Entities db = new Test1Entities();
BidDetail list = db.BidDetails.Find(ElementID);
db.BidDetails.Remove(list);
db.SaveChanges();
return "Deleted successfully";
}
}
}
I see many small small issues into your jqgrid code, which can be one of the reason of your current problem. You can change them in order to make the above code workable.
colModel items numbers are not exactly same as colNames items. You wrote Client Cost at first in colNames but in colModel you haven't used that.
You also haven't pasted your html code which is required to point jqgrid to load on table element.
for example:
<table id="grid" class="table table-bordered"></table>
<div id="pager"></div>
I am also assuming that you have already added free-jqgrid scripts and jquery-ui css files.
Also, in your c# code you can remove redundancy by using a global db initialization.
I have created a demo jqgrid which you can alter according your requirement:
<div class="row">
<table id="grid" class="table table-bordered"></table>
<div id="pager"></div>
</div>
#section Scripts{
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/free-jqGrid/jquery.jqgrid.min.js"></script>
<script type="text/javascript">
$(function () {
$("#grid").jqGrid
({
url: "/Home/GetBidValues",
datatype: 'json',
mtype: 'Get',
colNames: ['LanguageId', 'LanguageName', 'LanguageDescription', 'CreatedBy', 'CreatedOn'], //Othr Misc
//colModel takes the data from controller and binds to grid
colModel: [
//{ name: "act", template: "actions", align: "left", width: 58 },
{
key: true,
hidden: true,
name: 'LanguageId',
index: 'LanguageId',
editable: false
}, {
key: false,
name: 'LanguageName',
index: 'LanguageName',
frozen: true,
editable: true,
align: 'center'
}, {
key: false,
name: 'LanguageDescription',
index: 'LanguageDescription',
editable: true,
align: 'center'
}, {
key: false,
name: 'CreatedBy',
index: 'CreatedBy',
editable: true,
align: 'center'
}, {
name: 'CreatedOn',
index: 'CreatedOn',
editable: true,
align: 'center'
}],
//cmTemplate: { editable: true, autoResizable: true },
iconSet: "fontAwesome",
rowNum: 10,
//autoResizing: { compact: true },
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
pager: jQuery('#pager'),
toppager: false,
inlineEditing: { keys: true, position: "afterSelected" },
rownumbers: true,
sortname: "invdate",
sortorder: "desc",
caption: "Demonstration of the usage custom action buttons",
autowidth: true,
shrinkToFit: false,
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "LanguageId"
}
});
jQuery("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter:
false, defaultSearch: "cn", multipleSearch: true, searchOperators: true, search: true
}); //searchOnEnter: false means records are filtered as soon as the text is
entered by the user
jQuery("#grid").jqGrid('navGrid', '#pager', { add: true, edit: true, del: true, search: true, refresh: true,view:true }, {
// edit options
zIndex: 100,
url: '/Home/EditBid',
//datatype: 'json',
//mtype: 'Post',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {//add
zIndex: 100,
url: "/Home/CreateBid",
closeOnEscape: true,
closeAfterAdd: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {
// delete options
zIndex: 100,
url: "/Home/DeleteBid",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
reloadaftersubmit: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
</script>
}
I have view showing a list of documents using jqgrid. While I click on the document title in the grid, I created a pop up with partial view and in this partial view up am using Kendo tabs. In one of the tab am using a partial view to load a jqgrid which shows all the Document logs and in this grid my navgrid is not working. When i click on the next button for navigating to next page, it is actually navigating the main page where I have the list of documents. To avoid confusion I used different 'id' for the navgrid in the partial view, but then it showed no next and previous button at all. Could anyone guide me how to add paging to the partial view while not affecting the parent view.
Below is jqgrid code of the main View:
$.ajax(
{
type: "GET",
url: "#Url.Action("GetDocumentFileList", "Document")",
data: "",
dataType: "json",
success: function (data) {
if (data == "SessionTimeOut")
window.location.href = '#Url.Action("SessionTimeOut", "Error")';
var page = data.Page;
var rows = data.Rows;
var colModel = eval(data.Columns);
var colNames = eval(data.ColumnsTitle);
var $grid = $("#datagrid");
$grid.jqGrid({
url: "#Url.Action("GetDocumentFileList", "Document")",
datatype: griddataType,
datastr: rows,
colNames: colNames,
colModel: colModel,
gridComplete: initGrid,
rowList: [25, 50, 75, 100],
ignoreCase: true,
width: null,
shrinkToFit: true,
multiselect: true,
multiboxonly: false,
pager: '#navGrid',
sortname: 'DocumentRegisterID',
sortorder: "desc",
scrollerbar: true,
viewrecords: true,
rowNum: 25,
autowidth: true,
ondblClickRow: function (DocumentRegisterID) {
if (DocumentRegisterID && DocumentRegisterID !== lastsel2) {
$grid.jqGrid('restoreRow', lastsel2);
$grid.jqGrid('editRow', DocumentRegisterID, true, null, successFuncStandardGrid);
lastsel2 = DocumentRegisterID;
}
},
editurl: "#Url.Action("EditDocumentNo", "Document")",
hoverrows: true,
onSelectRow: function () {
return false;
},
here is the jqgrid code for the partial view used in the pop up in main view :
$.ajax(
{
type: "GET",
url: "#Url.Action("DocHistoryEventLog", "Document")",
data: '',
success: function (data) {
var page = data.Page;
var rows = data.Rows;
var $grid = $("#dataeventgrid");
$grid.jqGrid({
url: "#Url.Action("DocumentRegisterHistoryEventLogList", "Document", new { id = #docId })",
datatype: "json",
datastr: rows,
colNames: ['DocumentRegisterEventLogID', 'Event Type', 'Description', 'Revision', 'Version', 'Log By', 'Log Date', 'Organization Name', 'Document Owner Organization'],
colModel: [
{ name: 'DocumentRegisterEventLogID', index: 'DocumentRegisterEventLogID', key: true, hidden: true },
{ name: 'EventType', index: 'EventType', width: "20%", resizable: true },
{ name: 'EventDescription', index: 'EventDescription', sorttype: 'text', width: "20%", resizable: true },
{ name: 'Revision', index: 'Revision', width: "15%", sorttype: 'text', resizable: true },
{ name: 'DocVersion', index: 'DocVersion', width: "20%", resizable: true },
{ name: 'LogBy', index: 'LogBy', sorttype: 'text', width: "20%", resizable: true },
{
name: 'StrLogDate', index: 'StrLogDate', sorttype: 'text', width: "25%", resizable: true,
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDatepicker },
},
{ name: 'OrganizationName', index: 'OrganizationName', sorttype: 'text', width: "20%", resizable: true },
{ name: 'DocumetOwnerOrganizationName', index: 'DocumetOwnerOrganizationName', width: "20%", sorttype: 'text', resizable: true },
],
rowList: [15, 30, 45, 100],
loadonce: false,
shrinkToFit: true,
ignoreCase: true,
pager: '#navLogGrid',
autoencode: true,
sortname: 'DocumentRegisterEventLogID',
sortorder: "desc",
viewrecords: true,
rowNum: 15,
width: 850,
height:270,
gridview: true,
height: "auto",
scrollerbar: true,
loadComplete: function () {
highlightFilteredData.call(this);
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
$grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn", stype: 'select' });
$grid.jqGrid("navGrid", "#navLogGrid", { add: false, edit: false, del: false, search: false, refresh: true });
$grid.parents('div.ui-jqgrid-bdiv').css("max-height", '270px');
Setting the property loadonce:true in my partial view solved my problem. Thanks
Class that carries out CRUD functionality with a help of a stored proc
public class InsertUpdateDeleteBLL
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand();
public string InsertUpdateDeleteMethod(object param)
{
string returnValue = "";
try
{
Dictionary<string,> editData = param as Dictionary<string,>;
com.CommandText = "InsertUpdateDeleteSP";
com.CommandType = CommandType.StoredProcedure;
if (editData["oper"].ToString() == "del")
{
com.Parameters.AddWithValue("#UserID", editData["UserID"] == DBNull.Value ? 0 : editData["UserID"]);
com.Parameters.AddWithValue("#Actiontype", editData["oper"].ToString());
}
else
{
com.Parameters.AddWithValue("#UserID", editData["UserID"] == DBNull.Value ? 0 : editData["UserID"]);
com.Parameters.AddWithValue("#FirstName", editData["FirstName"].ToString());
com.Parameters.AddWithValue("#LastName", editData["LastName"].ToString());
com.Parameters.AddWithValue("#IsActive", editData["IsActive"].ToString());
com.Parameters.AddWithValue("#Department", editData["Department"].ToString());
com.Parameters.AddWithValue("#Email", editData["Email"].ToString());
com.Parameters.AddWithValue("#IsSuperAdmin", editData["IsSuperAdmin"].ToString());
com.Parameters.AddWithValue("#JobRole", editData["JobRole"].ToString());
com.Parameters.AddWithValue("#UserName", editData["UserName"].ToString());
}
com.Connection = conn;
conn.Open();
int m = com.ExecuteNonQuery();
if (m > 0)
{
if (editData["oper"].ToString() == "add")
{
returnValue = "Record Added Successfully";
}
else if (editData["oper"].ToString() == "edit")
{
returnValue = "Record Updated Successfully";
}
else if (editData["oper"].ToString() == "del")
{
returnValue = "Record Deleted Successfully";
}
else
{
throw new Exception("there is problem");
}
}
}
catch (Exception ex)
{
returnValue = ex.Message.ToString();
}
finally
{
conn.Close();
}
return returnValue;
}
//WebMethod
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string EditUpdateDelete(object data)
{
Helper.InsertUpdateDeleteBLL insertUpdateDelete = new Helper.InsertUpdateDeleteBLL();
string returnMessage = insertUpdateDelete.InsertUpdateDeleteMethod(data);
return returnMessage;
}
<script type="text/javascript">
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "MyTestPage.aspx/getData",
dataType: "json",
success: function (data) {
data = data.d;
$("#list").jqGrid({
datatype: "local",
colNames: ['UserID', 'First Name', 'Last Name', 'Is Active', 'Department', 'Email', 'Is Super Admin', "Job Role", 'Username'],
colModel: [
{ name: 'UserID', index: 'UserID', width: 50, stype: 'text' },
{ name: 'FirstName', index: 'FirstName', width: 130, stype: 'text', sortable: true, editable: true },
{ name: 'LastName', index: 'LastName', width: 130, editable: true },
{ name: 'IsActive', index: 'IsActive', width: 60, editable: false },
{ name: 'Department', index: 'Department', width: 80, align: "centre", sortable: true, editable: true },
{ name: 'Email', index: 'Email', width: 150, align: "centre", editable: true },
{ name: 'IsSuperAdmin', index: 'IsSuperAdmin', width: 150, align: "middle", editable: true },
{ name: 'JobRole', index: 'JobRole', width: 150, sortable: true, editable: true },
{ name: 'Username', index: 'Username', width: 100, sortable: true, editable: true }
],
data: JSON.parse(data),
rowno: 10,
loadonce: true,
multiselect: true,
rowlist: [5, 10, 20],
pager: '#pager',
viewrecords: true,
gridview: true,
sortorder: 'asc',
toppager: true,
editurl: 'MyTestPage.aspx/EditUpdateDelete',
cloneToTop: true,
async: false,
altrows: true,
autowidth: false,
hoverrows: true,
height: 200,
// rownumbers: true,
caption: "User Data"
});
$('#list').jqGrid('navGrid', '#pager',
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
cloneToTop: true
},
{
//update
recreateForm: true,
reloadAfterSubmit: false,
width: 500,
closeAfterEdit: true,
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata);
}
},
{
// add function
recreateForm: true,
beforeShowForm: function (form) {
$('#tr_UserID', form).hide();
},
width: 500,
reloadAfterSubmit: false,
closeAfterAdd: false,
ajaxEditOptions: { contentType: "application/json" },
//onclickSubmit: function (eparams) { alert('Hi');},
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata);
}
},
{
ajaxDelOptions: { contentType: "application/json" },
reloadAfterSubmit: false,
onclickSubmit: function (eparams) {
var retarr = {};
var sr = $("#list").getGridParam('selrow');
rowdata = $("#list").getRowData(sr);
retarr = { UserID: rowdata.UserID };
return retarr;
},
serializeDelData: function (data) {
var postData = { 'data': data };
return JSON.stringify(postData);
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
</script>
I have implemented the JqGrid in my application. I have done the edit,delete, insert operations but I am failing in searching the records. I have bind the data from the sql server.
Here is my script
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery.extend(jQuery.jgrid.edit, {
closeAfterEdit: true,
closeAfterAdd: true,
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata); ;
}
});
jQuery.extend(jQuery.jgrid.del, {
ajaxDelOptions: { contentType: "application/json" },
onclickSubmit: function (eparams) {
var retarr = {};
var sr = jQuery("#contactsList").getGridParam('selrow');
rowdata = jQuery("#contactsList").getRowData(sr);
retarr = { PID: rowdata.PID };
return retarr;
},
serializeDelData: function (data) {
var postData = { 'data': data };
return JSON.stringify(postData);
}
});
$.extend($.jgrid.defaults,
{ datatype: 'json' }
);
jQuery.extend(jQuery.jgrid.search, {
});
$("#contactsList").jqGrid({
url: '/WebService.asmx/GetListOfPersons1',
datatype: 'json',
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colNames: ['PID', 'First Name', 'Last Name', 'Gender'],
colModel: [
{ name: 'PID', width: 60, align: "center", hidden: true, searchtype: "integer", editable: true },
{ name: 'FirstName', width: 180, sortable: true, hidden: false, editable: true },
{ name: 'LastName', width: 180, sortable: false, hidden: false, editable: true },
{ name: 'Gender', width: 180, sortable: false, hidden: false, editable: true, cellEdit: true, edittype: "select", formater: 'select', editrules: { required: true },
editoptions: { value: getAllSelectOptions() }
}],
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'PID',
sortorder: "asc",
pager: jQuery('#gridpager'),
viewrecords: true,
gridview: true,
height: '100%',
editurl: '/WebService.asmx/EditRow',
// searchurl: '/WebService.asmx/Searchrow',
caption: 'Person details'
}).jqGrid('navGrid', '#gridpager', { edit: true, add: true, del: true, search: true });
jQuery("#contactsList").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, searchOperators: true });
// jQuery("#contactsList").setGridParam({ data: results.rows, localReader: reader }).trigger('reloadGrid');
jQuery("#contactsList").jqGrid('setGridParam', { url: "WebService.asmx/searchrow", page: 1 }).trigger("reloadGrid");
});
function getAllSelectOptions() {
var states = { 'male': 'M', 'female': 'F' };
return states;
}
</script>
Here I have given the reference for searching in my asmx file like WebService.asmx/searchrow when I click the find button in the popup the cursor is moving to the specified method in the url.
Here is my question how can I get the user entered search parameter name and value to that method to perform the search operation .
I have defined the searchrow method like following
[WebMethod]
public List<Person> searchrow(HttpContext context)
{
return null;
}
Please help me to out from this problem or any other alternative to do the search operation in JQGrid.
thanks
purna
Method resides inside Aspx page:
$("#list").jqGrid({
url: 'DirStructure.aspx/getData', //Not able get any data from here saw in firebug reponse is page itself instead of JSON data.
datatype: 'json',
mtype: 'POST',
colNames: ['pkLanguageID', 'Language'],
colModel: [
{ name: 'pkLanguageID', index: 'pkLanguageID', width: 30, align: 'left', stype: 'text', editable: false },
{ name: 'Language', index: 'Language', width: 80, align: 'left', stype: 'text', editable: true}],
rowNum: 5,
rowList: [10, 20, 30],
pager: '#pager',
sortname: 'pkLanguageID',
sortorder: 'desc',
caption: "Test Grid",
viewrecords: true,
async: false,
loadonce: true,
gridview: true,
width: 500,
loadComplete: function (result) {
alert(jQuery("#list").jqGrid('getGridParam', 'records'));
},
loadError: function (xhr) {
alert("The Status code:" + xhr.status + " Message:" + xhr.statusText);
}
});
Method resides inside DirStructure.aspx(Written WebMethod):
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getData()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
DataSet dsLang = new DataSet();
dsLang = CommonCode.CommonCode.GetIndividualLanguageList(7, 350027);
System.Diagnostics.Debug.Write(dsLang.GetXml());// Dataset for languages.
DataTable dt = dsLang.Tables[0];
System.Diagnostics.Debug.Write(GetJson(dt));
return GetJson(dt);
}
public static string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
I degugged this I am able to get JSON data here inside method but not able to view in jqgrid.
Please help me out.
Try getting data through AJAX call then populate to the grid.
Try this :-
In Code Behind For dummy data :-
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getData()
{
string data = GetJson();
return data;
}
public static string GetJson()
{
List<LanguageData> dataList = new List<LanguageData>();
LanguageData data1 = new LanguageData();
data1.pkLanguageID = 1;
data1.Language = "Language1";
dataList.Add(data1);
LanguageData data2 = new LanguageData();
data2.pkLanguageID = 2;
data2.Language = "Language2";
dataList.Add(data2);
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(dataList);
}
public class LanguageData
{
public int pkLanguageID { get; set; }
public string Language { get; set; }
}
In aspx page :-
$(document).ready(function () {
GetData();
});
function GetData() {
$.ajax({
type: "POST",
url: "../DirStructure.aspx/getData",
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: false,
success: function (response) {
var item = $.parseJSON(response.d);
if (item != null && item != "" && typeof (item) != 'undefined') {
$("#list").jqGrid({
url: '../Contact.aspx/getData',
data: item,
datatype: 'local',
colNames: ['pkLanguageID', 'Language'],
colModel: [
{ name: 'pkLanguageID', index: 'pkLanguageID', width: 30, align: 'left', stype: 'text', editable: false },
{ name: 'Language', index: 'Language', width: 80, align: 'left', stype: 'text', editable: true }],
rowNum: 5,
rowList: [10, 20, 30],
pager: '#pager',
sortname: 'pkLanguageID',
sortorder: 'desc',
caption: "Test Grid",
viewrecords: true,
async: false,
loadonce: true,
gridview: true,
width: 500,
loadComplete: function (result) {
alert(jQuery("#list").jqGrid('getGridParam', 'records'));
},
loadError: function (xhr) {
alert("The Status code:" + xhr.status + " Message:" + xhr.statusText);//Getting reponse 200 ok
}
});
}
else {
var result = '<tr align="left"><td>' + "No Record" + '</td></tr>';
$('#list').empty().append(result);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
}