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");
}
});
}
Related
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 would like to edit my data in grid. I can edit it in table and see it but I don't go to the c# method. I tried with ajax but it doesn't work too...Serialization doesn't work too. What is wrong?
[WebMethod]
public static string LoadData()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * from Employees", cn);
DataSet ds = new DataSet();
da.Fill(ds);
return JsonConvert.SerializeObject(ds.Tables[0]);
}
[WebMethod]
public void UpdateGrid()
{
//code to actually do the update to the database
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * from Employees", cn);
}
}
and JS:
$(document).ready(function () {
$("#btnEmployee").click(function () {
var service = "Default.aspx/LoadData";
var lastsel2;
$.ajax({
url: service,
datatype: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
method: "POST",
success: function (result) {
result = result.d;
jQuery("#EmpTable").jqGrid({
datatype: "local",
colNames : ['Emp numb', 'First name', 'Second name', 'Salary'],
colModel: [
{ name:"Emp_id", index: "Emp_id", width:80, editable: true},
{ name: "First_name", index: "First_name", width: 80, editable: true},
{ name: "Second_name", index: "Second_name", width: 80, editable: true},
{ name: "Salary", index: "Salary", width: 80, editable: true}
],
data: JSON.parse(result),
rowNum: 10,
loadonce: true,
rowList: [5, 10, 20],
pager: '#EmpPager',
viewrecords: true,
sortorder: 'asc',
gridview: true,
autowidth: true,
sortname: 'Emp_id',
altRows: true,
hoverrows: true,
onSelectRow: function (id) {
if (id && id !== lastsel2) {
jQuery('#EmpTable').restoreRow(lastsel2);
jQuery('#EmpTable').editRow(id, true);
lastsel2 = id;
}
},
caption: "Events",
cellurl: 'Default.aspx/UpdateGrid'
});
$("#EmpTable").jqGrid('navGrid', '#EmpPager', { edit: true, add: true, del: false });
$("#EmpTable").jqGrid('inlineNav', "#EmpPager");
},
error: function (error) {
alert("Oops!");
}
});
});
});
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
Script:
jQuery("#grid_table").jqGrid({
url: '#Url.Action("GetAll", "Widget")',
datatype: "json",
mtype: 'GET',
colNames: ['id', 'name'],
colModel: [
{ name: 'id', index: 'id', width: 55, sortable: true, editable: false, editoptions: { readonly: true, size: 10} },
{ name: 'name', index: 'name', width: 200, editable: true }
],
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
id: "id",
userdata: "userdata"
},
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery('#gridpager'),
sortname: 'name',
viewrecords: true,
sortorder: "asc",
caption: "Wines"
}).navGrid('#gridpager');
Controller:
public ActionResult GetAll()
{
List<object> list = new List<object>();
for (int i = 0; i < 20; i++)
{
var o = new
{
id = i.ToString(),
name = "name " + i.ToString()
};
list.Add(o);
}
var result = new
{
page = "1",
total = "1",
records = "10",
rows = list.ToArray()
};
string Jlist = Newtonsoft.Json.JsonConvert.SerializeObject(result);
return Json(Jlist, JsonRequestBehavior.AllowGet);
}
Json output:
And message: No records found!
What is the wrong with my code?
Thanks.
I think as mentioned in your json reader "userdata" is not there in your json .
So please pass some null value or any value in your userdata field.
Problem is this line:
string Jlist = Newtonsoft.Json.JsonConvert.SerializeObject(result);
I removed serilization line and then it works. Thanks for reply.
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
}