{"Message":"Invalid web service call, missing value for parameter: \u0027PersonID\u0027." - javascript

I'm trying to make ajax call to pull up data in jqgrid via asmx webservice but I'm getting this Invalid web service call, missing value for parameter error.
The function works well if I remove the input parameter in the web service call and ajax request but the issue persists once I have the input paramter.
Following is the web service method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public PersonsGrid Per(string PersonID)
{
....
return personsGrid;
}
Following is the Ajax call:
function getGridInfo() {
var personId = document.getElementById('txtPersonID').value;
$("#PersonsInfo").jqGrid({
url: '/Service/PersonsService.asmx/GetPersonsInfo',
data: "{'PersonID': '" + personId + "'}",
datatype: 'json',
mtype: 'POST',
async: false,
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" },
loadonce: false,
colNames: ['ID', 'FirstName', 'LastName', 'Email', 'Phone'],
colModel: [
{ name: 'FirstName', index: 'FirstName', width: 100 },
{ name: 'LastName', index: 'LastName', width: 100 },
{ name: 'Email', index: 'Email', width: 100 },
{ name: 'Phone', index: 'Phone', width: 100 }
],
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
rownumbers: true,
caption: 'Persons info',
loadError: function (xhr, textStatus, errorThrown) {
var error_msg = xhr.responseText;
var msg = "Some error occured during processing:";
msg += '\n\n' + error_msg;
alert(msg);
}
});
Any idea on how to overcome this issue. I followed several other posts but that still did not work. It has to do something with the data parameter in the ajax request.

The option
data: "{'PersonID': '" + personId + "'}"
contains two error:
jqGrid don't "know" data parameter, which exist in jQuery.ajax. Instead of that one can use postData parameter.
The string like {'PersonID': 'same_value'} is wrong JSON string, because JSON require to use " instead of '. You can fix the code by usage
If you use data or postData as JSON string then you should remove serializeGridData.
postData: '{"PersonID": "' + personId + '"}'
but such code will still contains bad code. I'd recommend you to use JSON.stringify instead, which convert an object to JSON string:
postData: JSON.stringify({PersonID: personId})
Alternatively you can remove data and postData and use the following serializeGridData:
serializeGridData: function () {
return JSON.stringify({PersonID: personId});
}
Such callback function ignores the standard parameter, which send jqGrid and it will send PersonID parameter in JSON format instead.

Have you tried changing
data: "{'PersonID': '" + personId + "'}",
to
postData: "{'PersonID': '" + personId + "'}",
as you appear to be referencing postData in the serializeGridData function.

By definition postData parameter is a object and it can't be a string. More of the type of parameters can be read here
So, IMHO the clear solution is to set a postData as object and use serializeGridData like this:
...jqGrid({
...
postData : { "PersonID" : personId },
serializeGridData : function( postData ) {
return JSON.stringify(postData);
},
...
});
Kind Regards

Related

Sending Array Object Data in Javascript to ASP.NET Core Controller using AJAX ()

I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!

jQuery .ajax() - add query parameters to POST request?

To add query parameters to a url using jQuery AJAX, you do this:
$.ajax({
url: 'www.some.url',
method: 'GET',
data: {
param1: 'val1'
}
)}
Which results in a url like www.some.url?param1=val1
How do I do the same when the method is POST? When that is the case, data no longer gets appended as query parameters - it instead makes up the body of the request.
I know that I could manually append the params to the url manually before the ajax request, but I just have this nagging feeling that I'm missing some obvious way to do this that is shorter than the ~5 lines I'll need to execute before the ajax call.
jQuery.param() allows you to serialize the properties of an object as a query string, which you could append to the URL yourself:
$.ajax({
url: 'http://www.example.com?' + $.param({ paramInQuery: 1 }),
method: 'POST',
data: {
paramInBody: 2
}
});
Thank you #Ates Goral for the jQuery.ajaxPrefilter() tip. My problem was I could not change the url because it was bound to kendoGrid and the backend web API didn't support kendoGrid's server paging options (i.e. page, pageSize, skip and take). Furthermore, the backend paging options had to be query parameters of a different name. So had to put a property in data to trigger the prefiltering.
var grid = $('#grid').kendoGrid({
// options here...
dataSource: {
transport: {
read: {
url: url,
contentType: 'application/json',
dataType: 'json',
type: httpRequestType,
beforeSend: authentication.beforeSend,
data: function(data) {
// added preFilterMe property
if (httpRequestType === 'POST') {
return {
preFilterMe: true,
parameters: parameters,
page: data.page,
itemsPerPage: data.pageSize,
};
}
return {
page: data.page,
itemsPerPage: data.pageSize,
};
},
},
},
},
});
As you can see, the transport.read options are the same options for jQuery.ajax(). And in the prefiltering bit:
$.ajaxPrefilter(function(options, originalOptions, xhr) {
// only mess with POST request as GET requests automatically
// put the data as query parameters
if (originalOptions.type === 'POST' && originalOptions.data.preFilterMe) {
options.url = options.url + '?page=' + originalOptions.data.page
+ '&itemsPerPage=' + originalOptions.data.itemsPerPage;
if (originalOptions.data.parameters.length > 0) {
options.data = JSON.stringify(originalOptions.data.parameters);
}
}
});

Properly Initialize Client Side Model

My issue is very simple. I am using ASP Web API, Entity Framework, Angular, and Kendo UI. I have 2 classes, FREQUENCY and FREQ_TYPE_. Class FREQUENCY has a navigation property to class FREQ_TYPE. I have a kendo ui grid that loads 10 class FREQUENCY models. Each class FREQUENCY model has it's FREQ_TYPE data loaded properly. My problem is that when I create a new row in my kendo ui grid and try to save the row to the server, I get an error saying the navigation property FREQ_TYPE needs to be initialized. This is expected of course since kendo doesn't know how to auto=initialize my nav properties.
What is the best practice for giving my angular JS client the knowledge it needs to create a new class FREQ_TYPE so I can properly initialize class FREQUENCY and save it to the server? My models only exist as code-first entity models, so I can't just create a new model in my client side JS as it doesn't know about these models. Is there some framework that can generate local model classes from an EF database? Or do I just have to manually set all the json fields for my class FREQ_TYPE navigation property? Or is there an easier way for me to use Web API so that I can make a request to "figure out" what the model info is and create a client side JS model without needing to have a "local model"?
Here is the client side grid and datasource:
$(document).ready(function () {
var crudServiceBaseUrl = "http://localhost:29858/";
var NIICDDS = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "api/NIICDFreq",
dataType: "json"
},
update: {
url: function (data) {
console.log("DATA TEST");
console.log(data);
return crudServiceBaseUrl + "api/NIICDFreq/";
},
// url: crudServiceBaseUrl + "api/VHFMasterLists",
dataType: "json",
data: function (data) {
console.log("returning data in update TEST");
console.log(data.models[0]);
return data.models[0];
},
type: "PUT",
contentType: "application/json; charset=utf-8",
},
destroy: {
url: crudServiceBaseUrl + "api/NIICDFreq",
dataType: "json"
},
create: {
url: crudServiceBaseUrl + "api/NIICDFreq",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8"
},
parameterMap: function (model, operation) {
if (operation !== "read" && model) {
return kendo.stringify(model);
} else {
return kendo.stringify(model) ;
}
}
},
batch: true,
pageSize: 20,
schema: {
data: function (data) { //specify the array that contains the data
console.log("DATA RETURN TEST");
console.log(data);
return data || [];
},
model: {
id: "Id",
fields: {
Id: { editable: false,
nullable: false,
type: "number"
},
Frequency: { type: "string" }
}
}
}
});
$("#NIICDFreqGrid").kendoGrid({
dataSource: NIICDDS,
columns: [
{ field: "Id", title: "Freq ID", format: "{0:c}", width: "120px" },
{ field: "Frequency", title: "Frequency Test", format: "{0:c}", width: "120px" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }
],
toolbar: ["create"],
editable: "inline"
});
});
And here is the web api controller:
[ResponseType(typeof(FREQUENCY))]
public IHttpActionResult PostFREQUENCY(FREQUENCY testfreq)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.FREQUENCIES.Add(testfreq);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (FREQUENCYExists(testfreq.Id))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = testfreq.Id }, testfreq);
}
The error is the last line:
iisexpress.exe Information: 0 : Request, Method=POST, Url=http://localhost:29858/api/NIICDFreq, Message='http://localhost:29858/api/NIICDFreq'
iisexpress.exe Information: 0 : Message='NIICDFreq', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='CFETSWebAPI.Controllers.Frequency.NIICDFreqController', Operation=DefaultHttpControllerActivator.Create
iisexpress.exe Information: 0 : Message='CFETSWebAPI.Controllers.Frequency.NIICDFreqController', Operation=HttpControllerDescriptor.CreateController
iisexpress.exe Information: 0 : Message='Selected action 'PostFREQUENCY(FREQUENCY testfreq)'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Message='Value read='DomainModelModule.FREQUENCY'', Operation=JsonMediaTypeFormatter.ReadFromStreamAsync
iisexpress.exe Information: 0 : Message='Parameter 'testfreq' bound to the value 'DomainModelModule.FREQUENCY'', Operation=FormatterParameterBinding.ExecuteBindingAsync
iisexpress.exe Information: 0 : Message='Model state is invalid.
testfreq.FREQ_POOL: The FREQ_POOL field is required.,testfreq.FREQ_TYPE: The FREQ_TYPE field is required.', Operation=HttpActionBinding.ExecuteBindingAsync
And of course testfreq has all null values.
Thank you for your help.
Since you shared no code, I can only make an assumption. However, I think you're confused with the error message. Neither Kendo or Angular are responsible. They do not "initialize" classes. You said yourself, the data is there on the client.
From what it sounds like to me, the data arrives at your controller action, and the compiler does not know how to initialize your class. Make sure your Class B has a constructor defined in your server-side code. Even an empty constructor will suffice, unless the members of the class need explicit initialization themselves.
public class B {
// constructor
public B() {
// initialize class members
}
}

Webmethod not firing in FlexiGrid

I'm using FlexiGid for my project.But the problem is WebMethod not firing.(Json/Ajax call)
I have put a Debug point to the Webmethod but it's not firing and also Firebug shows the web method Url is correct.
Here i have put the code
Ajax Call
function flexgrid() {
debugger;
$("#flex1").flexigrid({
url: '/WebMethods.aspx/GetIssueSummaryById',
dataType: 'json',
contentType: "application/json; charset=utf-8",
colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'center'},
],
data: JSON.stringify({ ProjectId: "1", UserId: "1" }), //Hard code this values at this time
buttons : [
{ name: 'Add', bclass: 'add', onpress: test },
{ name: 'Delete', bclass: 'delete', onpress: test },
{separator: true},
{name: 'A', onpress: sortAlpha},
{name: 'B', onpress: sortAlpha}
],
searchitems : [
{ display: 'Project', name: 'project' },
{display: 'Name', name : 'name', isdefault: true}
],
sortname: "id",
sortorder: "asc",
usepager: true,
title: 'Issue Summary',
useRp: true,
rp: 10,
showTableToggleBtn: true,
width: 1000,
height: 500
});
};
Web Method( thats in WebMethods.aspx file )
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<IssuesVM> GetIssueSummaryById(string UserId, string ProjectId)
{
//Guid LoggedInUserId = new Guid(UserId);
//int ProjectId = Convert.ToInt32(ProjectId);
List<IssuesVM> lst = new List<IssuesVM>();
try
{
SqlCommand comIssueSummary = new SqlCommand("SP_GetIssuesByProjectIDAndOwnerId", conn);
comIssueSummary.CommandType = CommandType.StoredProcedure;
//comIssueSummary.Parameters.Add("#ProjectId", SqlDbType.Int).Value = ProjectId;
// comIssueSummary.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = LoggedInUserId;
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlDataReader rdr = comIssueSummary.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
//Some code goes here
}
}
catch (Exception)
{
throw;
}
return lst;
}
After that Firebug shows this
Image Here
Can anyone know the Error for this ? Not firing webmethod ?
P.S - I saw some solution in below post[Click Here], I did thatone to the flexigrid.js file but it also not working.
Here is the Change
FlexiGrid.js file (before change )
$.ajax({
type: p.method,
url: p.url,
data: param,
dataType: p.dataType,
success: function (data) {
g.addData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
},
FlexiGrid.js (After Change )
$.ajax({
contentType: "application/json; charset=utf-8",
data: "{}", // to pass the parameters to WebMethod see below
success: function (data) {
g.addData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
},
So first off, it might be a good idea to move this to a WebService.asmx file. It is just best and common practice to do so. .ASPX pages respond with HTML/CSS/Javascript normally and .asmx responds with JSON or XML.
Either way, whether the Ajax calls for flexigrid are to a WebService or a Web Forms page, when you add the attribute [WebMethod] to expose a method doing the first Ajax call can be a bit challenging. There is something a bit finicky about Ajax calls to public WebMethods. The finicky arises around the content-type of the request and if the request is JSON or XML and if the response is JSON or XML.
So I am going to show you what I know works for a project I used Flexigrid:
$('#gridTablegSearchProperty').flexigrid({
url: 'Services/WSgSearch.asmx/gridTablegSearchProperty',
colModel: [...
You will notice in the first code snippet I do not set the contentType or the dataType properties of Flexigrid.
And now my WebMethod signature
[WebMethod]
public XmlDocument gridTablegSearchProperty()
{
System.Collections.Specialized.NameValueCollection nvc = HttpContext.Current.Request.Form;
int pgNum = nvc.GetValueAsInteger("page").GetValueOrDefault(1);
int pgSize = nvc.GetValueAsInteger("rp").GetValueOrDefault(20);
string sortName = nvc.GetValueOrDefaultAsString("sortname", "key");
string sortOrder = nvc.GetValueOrDefaultAsString("sortorder", "desc");
string query = nvc.GetValueOrDefaultAsString("query", string.Empty);
string qtype = nvc.GetValueOrDefaultAsString("qtype", string.Empty);
My WebMethod is in a .asmx file, it will not matter if you keep yours in a code behind file but I would move to a WebService and drop the WebMethods.aspx this is poor naming convention and file use convention.

How to display the searched data on the jgrid

this is related to my previous question about jqgrid. im doing now a search button that would search my inputed text from the server and display those data (if there is) in the jqgrid. Now, what i did is i create a global variable that stores the filters. Here's my javascript code for my searching and displaying:
filter = ''; //this is my global variable for storing filters
$('#btnsearchCode').click(function(){
var row_data = '';
var par = {
"SessionID": $.cookie("ID"),
"dataType": "data",
"filters":[{
"name":"code",
"comparison":"starts_with",
"value":$('#searchCode').val(),
}],
"recordLimit":50,
"recordOffset":0,
"rowDataAsObjects":false,
"queryRowCount":true,
"sort_descending_fields":"main_account_group_desc"
}
filter="[{'name':'main_account_group_code','comparison':'starts_with','value':$('#searchCode').val()}]";
$('#list1').setGridParam({
url:'json.php?path=' + encodeURI('data/view') + '&json=' + encodeURI(JSON.stringify(par)),
datatype: Settings.ajaxDataType,
});
$('#list1').trigger('reloadGrid');
$.ajax({
type: 'GET',
url: 'json.php?' + $.param({path:'data/view',json:JSON.stringify(par)}),
dataType: Settings.ajaxDataType,
success: function(data) {
if ('error' in data){
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
if ( (JSON.stringify(data.result.main.row)) <= 0){
alert('code not found');
}
else{
var root=[];
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
});
root[rowIndex] = row;
row_data += JSON.stringify(root[rowIndex]) + '\r\n';
});
}
alert(row_data); //this alerts all the data that starts with the inputed text...
}
}
});
}
i observed that the code always enter this (i am planning this code to use with my other tables) so i put the filter here:
$.extend(jQuery.jgrid.defaults, {
datatype: 'json',
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("ID"),
'dataType': 'data',
'filters': filter,
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
});
now, my question is, why is it that that it displayed an error message "Server Error: Parameter 'dataType' is not specified"? I already declared dataType in my code like above but it seems that its not reading it. Is there anybody here who can help me in this on how to show the searched data on the grid?(a function is a good help)
I modified your code based on the information from both of your questions. As the result the code will be about the following:
var myGrid = $("#list1");
myGrid.jqGrid({
datatype: 'local',
url: 'json.php',
postData: {
path: 'data/view'
},
jsonReader: {
root: function(obj) {
var root = [], fields;
if (obj.hasOwnProperty('error')) {
alert(obj.error['class'] + ' error: ' + obj.error.msg);
} else {
fields = obj.result.main.metadata.fields;
$.each(obj.result.main.rowdata, function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
row[fields[columnIndex].name] = rowArrayValue;
});
root.push(row);
});
}
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var filter = JSON.stringify([
{
name:'main_account_group_code',
comparison:'starts_with',
value:$('#searchCode').val()
}
]);
var jsonParams = {
SessionID: $.cookie("ID"),
dataType: 'data',
filters: filter,
recordLimit: postData.rows,
recordOffset: postData.rows * (postData.page - 1),
rowDataAsObjects: false,
queryRowCount: true,
sort_descending_fields:'main_account_group_desc',
sort_fields: postData.sidx
};
return $.extend({},postData,{json:JSON.stringify(jsonParams)});
},
loadError: function(xhr, msg, e) {
alert('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Code', 'Description','Type'],
colModel:[
{name:'code'},
{name:'desc'},
{name:'type'}
],
rowNum:10,
viewrecords: true,
rowList:[10,50,100],
pager: '#tblDataPager1',
sortname: 'desc',
sortorder: 'desc',
loadonce:false,
height: 250,
caption: "Main Account"
});
$("#btnsearchCode").click(function() {
myGrid.setGridParam({datatype:'json',page:1}).trigger("reloadGrid");
});
You can see the code live here.
The code uses datatype:'local' at the beginning (at the 4th line), so you will have no requests to the server if the "Search" button is clicked. The serializeGridData the data from the postData parameter of serializeGridData will be combined with the postData parameter of jqGrid (the parameter "&path="+encodeURIComponent('data/view') will be appended). Additionally all standard jqGrid parameters will continue to be sent, and the new json parameter with your custom information will additionally be sent.
By the way, if you want rename some standard parameters used in the URL like the usage of recordLimit instead of rows you can use prmNames parameter in the form.
prmNames: { rows: "recordLimit" }

Categories

Resources