Kendo UI datasource not triggering transport :Create - c#

I've 2 kendoUI grids doing CRUD from a web service. For some reason, read command works perfectly and populates my grid. But the create is not triggering in the UserEventGrid() method.
Here is my current situation. I have a grid that displays first. When I click on Add it opens a lookup grid when I select an item from that grid it opens a window with the selected row. That has
a Add button. Now when I click on this Add the transport : Create is not triggered.
UserEventGrid() this is the main Grid[First Grid].This has addentry button(It triggers addEntry(e))
namesListGrid() this is the second grid that populates after clicking lookup. After selecting row on the new window it has add button.(It triggers add(dataItem) and respective transport . Here comes the
issue. It's not triggering the transport Create.
Below is my code.
function UserEventGrid() {
userDS = new kendo.data.DataSource({
type: "json",
schema: {
data: function (response) {
return JSON.parse(response.d);
},
model: {
id: "UserId",
fields: {
UserId: { editable: false, nullable: false, type: "string" },
FirstName: { editable: true, nullable: true, type: "string" },
LastName: { editable: true, nullable: true, type: "string" },
},
},
transport: {
read: {
url: "/Services/Services.asmx/getUsers",
contentType: "application/json; charset=utf-8",
type: "POST",
},
create: {
url: "/Services/Services.asmx/AddUsers",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json"
},
update: {
url: "/Services/Services.asmx/UpdateUsers",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json"
},
destroy: {
url: "/Services/Services.asmx/DeleteUsers",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json"
},
parameterMap: function (data, type) {
if ((type == "update") || (type == "create") || (type == "destroy")) {
console.log('parameterMap: data => ' + JSON.stringify(data));
return JSON.stringify({ "erpUserJson": data });
} else {
return data;
}
}
}
});
userGrid = $("#user-event-grid").kendoGrid({
dataSource: userDS,
height: 450,
pageable: false,
sortable: true,
autosync: true,
binding: true,
columns: [
{
field: "Active",
title: "Active",
headerTemplate: '<span class="tbl-hdr">Active</span>',
template: '<input type="checkbox" #= Active ? "checked=checked" : "" # disabled="disabled" ></input>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
},
width: 65
},
{
field: "FirstName",
title: "FirstName",
headerTemplate: '<span class="tbl-hdr">FirstName</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
{
field: "LastName",
title: "LastName",
headerTemplate: '<span class="tbl-hdr">LastName</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
,
{
command: [
{
name: "destroy",
template: "<div class='k-button delete-btn'><span class='k-icon k-delete'></span></div>",
text: "remove"
},
{
text: "Edit",
template: "<div class='k-button edit-btn'><span class='k-icon k-edit'></span></div>",
click: editEntry
},
],
width: 90,
attributes: {
style: "vertical-align: top; text-align: center;"
}
},
],
editable: "popup"
}).data('kendoGrid');
}
function namesListGrid() {
nameDS = new kendo.data.DataSource({
type: "json",
schema: {
data: function (response) {
return JSON.parse(response.d);
},
model: {
id: "Z_CIM_WRK_ID",
fields: {
Z_NAMEFIRST: { editable: false, nullable: false, type: "string" },
Z_NAMELAST: { editable: false, nullable: true, type: "string" },
EMAILID: { editable: false, nullable: true, type: "string" },
}
},
},
transport: {
read: {
url: "/Services/Services.asmx/getNames",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
data: getSearchCriteria()
},
parameterMap: function (data, type) {
if ((type == "read") || (type == "create") || (type == "destroy")) {
console.log("parametermap => " + JSON.stringify(data));
return JSON.stringify(data);
} else {
return data;
}
}
}
});
namesGrid = $("#second").kendoGrid({
dataSource: nameDS,
height: 450,
pageable: false,
sortable: true,
binding: true,
selectable: "row",
serverFiltering: true,
autoSync: true,
columns: [
{
field: "Z_EID",
title: "ID",
headerTemplate: '<span class="tbl-hdr">ID</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
{
field: "Z_NAMELAST",
title: "ZNAMELAST",
headerTemplate: '<span class="tbl-hdr">ZNAMELAST</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
{
field: "Z_NAMEFIRST",
title: "ZNAMEFIRST",
headerTemplate: '<span class="tbl-hdr">ZNAMEFIRST</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
],
change: function (e) {
var dataItem = this.dataItem(this.select());
$("#third").hide(true);
$("#second").hide(true);
$("#first").show(true);
$("#gtable").show(true);
add(dataItem);
}
}).data('kendoGrid');
}
function add(dataItem) {
console.log(JSON.stringify(dataItem));
var model = {
"UserId": dataItem.Z_EID,
"FirstName": dataItem.Z_NAMEFIRST,
"LastName": dataItem.Z_NAMELAST,
"Group": "OPS",
"EmailAddr": dataItem.EMAILID,
"MobilePhone": dataItem.PHONE,
};
var viewModel = kendo.observable({
data: model,
isAddMode: true,
isLookupMode:false,
isEditMode: false,
groups: userGroups,
closeWin: function (dataItem) {
console.log('data => ' + JSON.stringify(this.data));
console.log("BEFORE => " + JSON.stringify(userDS.data()));
userDS.add(this.data);
userDS.sync();
var editWin = $("#window");
editWin.data("kendoWindow").close();
},
});
kendo.bind($("#edit-win"), viewModel);
$("#palette").html('');
$("#palette").append('<div id="palette-widget"></div>');
$('#window').data("kendoWindow").center().open();
}
function addEntry(e) {
var model = {
"UserId": "",
"FirstName": '',
"LastName": '',
};
var viewModel = kendo.observable({
data: model,
isAddMode: false,
isLookupMode:true,
isEditMode: false,
filterable:true,
groups: userGroups,
closeWin: function (e) {
console.log('data => ' + JSON.stringify(this.data));
userDS.add(this.data);
var editWin = $("#window");
editWin.data("kendoWindow").close();
e.preventDefault();
},
LookupWin: function (e) {
namesListGrid();
},
});
kendo.bind($("#edit-win"), viewModel);
$("#palette").html('');
$("#palette").append('<div id="palette-widget"></div>');
$('#window').data("kendoWindow").center().open();
}

In your addEntry function, you do add data to the dataSource like this:
userDS.add(this.data);
However, you never call the userDS.sync() (you do it in the add function but not addEntry). You did set the autosync property to true, which would have triggered the create event, but instead of doing on the userDS dataSource, you did it on the userGrid. You can either set the autosync to true in the userDS dataSource or call the userDS.sync() after the userDS.add.

Related

A public action method 'xyz' was not found on controller

I have Kendo Grid in my view. I have specified read , edit and delete each as of type HTTPPOST. But when I try to edit or delete i get an error that : "A public action method 'UpdateDetails' was not found on controller 'Nop.Plugin.Misc.CategoryWiseShipping.Controllers.ShippingChargeController'." for update Action and similarly one other for delete option.
Interesting thing is that it works fine on my local machine but throws error when published to server
I have searched extensivelly on google but couldn't find the reason as to why it is happening.
This is the controller actionMethod
[HttpPost]
public ActionResult UpdateDetails(ShippingChargeModel shippingChargeModel)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
return AccessDeniedView();
if (shippingChargeModel.SchoolEmail == null)
{
ErrorNotification(" Email can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleStartDate == null)
{
ErrorNotification(" Sale start date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate == null)
{
ErrorNotification(" Sale end date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate < shippingChargeModel.SaleStartDate)
{
ErrorNotification(" Sale start date should be less than sale end date!!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
var modelFromDb = _catShippingService.GetRecord(shippingChargeModel.Id);
modelFromDb.SaleEndDate = shippingChargeModel.SaleEndDate.Value.AddMinutes(330);
modelFromDb.SaleStartDate = shippingChargeModel.SaleStartDate.Value.AddMinutes(330);
modelFromDb.SchoolEmail = shippingChargeModel.SchoolEmail;
modelFromDb.ShippingCharge = shippingChargeModel.ShippingCharge;
modelFromDb.ModifyDate = DateTime.Now;
_catShippingService.Update(modelFromDb);
return new NullJsonResult();
}
This is my Kendo Grid :
function loadKendo() {
var dataNew = {};
$("#shippingCharge-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
},
update: {
url: "#Html.Raw(Url.Action("UpdateDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
//data: addAntiForgeryToken
},
destroy: {
url: "#Html.Raw(Url.Action("DeleteDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
}
,
parameterMap: function (data, operation) {
if (operation === "update") {
dataNew.Id = data.Id;
dataNew.CategoryId = data.CategoryId;
dataNew.ShippingCharge = data.ShippingCharge;
dataNew.SaleStartDate = stringToTimestamp(data.SaleStartDate.toUTCString());
dataNew.SaleEndDate = stringToTimestamp(data.SaleEndDate.toUTCString());
dataNew.SchoolEmail = data.SchoolEmail;
return { ShippingChargeModel: dataNew };
}
return data;
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
//ProductId: { editable: false, type: "number" },
CategoryId: { editable: false, type: "string" },
CategoryName: { editable: false, type: "string" },
ShippingCharge: { editable: true, type: "number" },
SaleStartDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SaleEndDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SchoolEmail: { editable:true, type: "string" }
}
}
},
requestEnd: function (e) {
if (e.type == "update") {
this.read();
}
if (e.type == "cancel") {
this.cancelChanges();
}
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info: false,
pageSizes: [#(gridPageSizes)]
},
editable: {
confirmation: "#T("Admin.Common.DeleteConfirmation")",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "CategoryName",
title: "CategoryName",
width: 300
},
{
field: "ShippingCharge",
title: "Shipping Charge",
width: 100,
encoded: false
}
,
{
field: "SchoolEmail",
title: "Email",
width: 200,
encoded: false
}
,
{
field: "SaleStartDate",
title: "Sale Start Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleStartDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
},
{
field: "SaleEndDate",
title: "Sale End Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleEndDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
}, {
command: [
{
name: "edit",
text: {
edit: "#T("Admin.Common.Edit")",
update: "#T("Admin.Common.Update")",
cancel: "#T("Admin.Common.Cancel")"
}
}
, {
name: "destroy",
text: "#T("Admin.Common.Delete")"
}
],
width: 200
}
]
});
}
Please help me out. Any sort of insight will do ...

Telerik Kendo Grid editing inline with kendo treeview editor template

I have a kendo grid that is edited inline. One of the fields should be edited selecting an element from a list, but the list must have a hierarchical structure (would be nice be able of filter that list). I was thinking in use a kendo treeview as editor for that field but I haven't found any way to accomplish this. I tried make a custom editor template (using columns.Bound(s => s.FieldId).EditorTemplateName("_TreeEditorTemplate")) that render the treeview, but the treeview is not an input and is not selectable. I also thinked in make an editor that use a kendo dropdownlist with the tree inside but this is no currently supported by kendo. Any ideas???
Have you looked at the sample on the Kendo site: https://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Editing/use-treeview-as-grid-editor
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "//demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1 } },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
},
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
edit: function (e) {
//checking if a cell from the Test column is opened for editing
var dummyInput = e.container.find("input[name='test']");
if (dummyInput.length > 0) {
var treeView = $(e.container).find(".treeViewEditor").data("kendoTreeView");
var originalItem = treeView.findByText(dummyInput.val());
if (originalItem != null) {
// Select the item based on the field value
treeView.select(originalItem);
}
}
},
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{
field: "test", title: "Test", width: 120,
editor: function (container, options) {
var input = $("<input class='tveInput'/>");
input.attr("name", options.field);
var tvDiv = $("<div class='treeViewEditor'></div>");
$(tvDiv).kendoTreeView({
animation: false,
dataSource: [
{
text: "foo1"
},
{
text: "foo2",
items: [
{ text: "bar" },
{ text: "bar1" },
{ text: "bar2" }
]
}
]
});
var treeView = $(tvDiv).data("kendoTreeView");
$(tvDiv).find(".k-in").mousedown(function (e) {
var clickedNode = $(e.toElement).closest("[role=treeitem]");
var dataItem = treeView.dataItem(clickedNode);
var dummyInput = clickedNode.closest("[role=gridcell]").find("input[name='test']");
dummyInput.val(dataItem.text);
dummyInput.trigger("change");
});
tvDiv.appendTo(container);
input.appendTo(container);
}
},
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 },
{ field: "Discontinued", width: 120 },
{ command: "destroy", title: " ", width: 150 }],
editable: true
});
});
</script>
</div>
<style>
.tveInput {
display: none;
}
</style>

Edit and add features functionality not working in jqgrid

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>

How to perform the search operation in server side in jQGrid using c#?

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

jqGrid: Problem using editurl to call RESTful method

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
}

Categories