jqgrid form editing editoptions select ajax add parameter - asp.net

i'm trying to build a select element in the form editing jqgrid by calling an ajax webmethod (asp.net).
Everythings work great if I call a method without parameter. It doesn't work if I try to call a webmethod expecting a string parameter:
this is an extract of the code:
ajaxSelectOptions: { type: "POST", contentType: 'application/json; charset=utf-8', },
colNames: ['City', 'State'],
colModel: [
{
name: 'City',
index: 'City',
align: "center",
width: 80,
searchoptions: { sopt: ['eq', 'ne', 'cn']} ,
edittype: 'select',
editable: true,
editrules: { required: true },
editoptions: {
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceGeographic.asmx/GetCityByState") %>',
buildSelect: function (data) {
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
var s = '<select id="customer_City" name="customer_City">';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
s += '<option value="' + response[i]["Id"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return s + "</select>";
}
}
},
...
where can i set the parameter to send to the GetCityByState webmethod?
EDIT: I did not highlight that I'm using POST to call webmethod. Even if i tried as Oleg suggested on this link, it doesn't work :(

I think you need ajaxSelectOptions parameter of jqGrid. For example if you need to have the id of the selected row as an additional id parameter sent to webmethod identified by dataUrl you can use data parameter of ajaxSelectOptions in function form:
ajaxSelectOptions: {
type: "GET", // one need allows GET in the webmethod (UseHttpGet = true)
contentType: 'application/json; charset=utf-8',
dataType: "json",
cache: false,
data: {
id: function () {
return JSON.stringify($("#list").jqGrid('getGridParam', 'selrow'));
}
}
}
because in the code above the parameter dataType: "json" are used you should modify the first line of buildSelect from
buildSelect: function (data) {
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
...
to
buildSelect: function (data) {
var response = $.parseJSON(data.d);
...
Moreover because you use the line $.parseJSON(data.d) I can suppose that you return the data from the webmethod in the wrong way. Typically the type of return value from the webmethod should be class. You should don't include any call of manual serialization of the returned object. Instead of that some people misunderstand that and declare string as the return type of the webmethod. They makes JSON serialization manually with call of DataContractJsonSerializer or JavaScriptSerializer. As the result the manual serialized data returned as string will be one more time serialized. It's the reason why you can have two calls of $.parseJSON: var retValue = $.parseJSON(data); var response = $.parseJSON(retValue.d);. If you will be use dataType: "json" inside of ajaxSelectOptions and if you would do no manual serialization to JSON in web method and just rejurn the object like it be, you would need to have no call of $.parseJSON at all. You can just use directly data.d:
buildSelect: function (data) {
var response = data.d;
...

Related

Ajax data not passing to controller

I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.
Here my function:
function functionA() {
$.ajax({
url: URLToApi,
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
data: {
access_token: sessionStorage.getItem('pageToken'),
message: $('#comment').val(),
id: sessionStorage.getItem('pageId')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
Check below things in Controller's action that
there should be a matching action in controller
name of parameter should be same as you are passing in data in ajax
Method type should be same the ajax POST of the action in controller.
function AddPayment(id, amount) {
var type = $("#paymenttype").val();
var note = $("#note").val();
var payingamount = $("#amount").val();
$('#addPayment').preloader();
$.ajax({
type: "POST",
url: "/Fixed/AddPayment",
data: {
id: id,
amount: payingamount,
type: type,
note: note
},
success: function (data) {
}
});
}
Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:
function functionA() {
$.ajax({
url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}

why is my jqGrid is empty eventhough json data is present

Here is my jqGrid, that is not displaying any data.
I'm getting the json response for the grid, but it is not displaying.
Here is what i've done so far.
<script type="text/javascript">
$.jgrid.no_legacy_api = true;
function getCompanyData() {
//debugger;
$.ajax({
url: "jqGrid_pureJS.aspx/GetCompanyList",
data: "{}", // "{}" For empty input data use "{}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
//debugger;
var grdData = $("#jqGrid")[0];
grdData.addJSONData(result.d);
},
error: function (result) {
//debugger;
}
});
}
$(function () {
$("#jqGrid").jqGrid({
datatype: getCompanyData,
colNames: ['Id', 'Name', 'Address', 'City', 'Phone'],
colModel: [
{ name: 'F1', index: 'invid', width: 55 },
{ name: 'F2', index: 'invdate', width: 90,editable:true },
{ name: 'F3', index: 'amount', width: 80,editable:true, align: 'right' },
{ name: 'F4', index: 'tax', width: 80,editable:true, align: 'right' },
{ name: 'F5', index: 'total', width: 80,editable:true, align: 'right' }
],
pager: $("#pager"),
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
caption: 'My first grid',
width:800
}).navGrid('#pager', { edit:true,view: true, del: false });
});
</script>
And here is my webmethod that posts data.
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json,UseHttpGet=false)]
public static string GetCompanyList()
{
var data = GetAllData();
try
{
string response = JsonConvert.SerializeObject(data, Formatting.Indented);
return response;
}
catch (Exception ex)
{
return ex.Message;
}
}
And here is my json responce captured:
{"d":"
[\r\n
{\r\n
\"F1\": 1.0,\r\n
\"F2\": \"Name\",\r\n
\"F3\": \"Address\",\r\n
\"F4\": \"City\",\r\n
\"F5\": \"Phone\"\r\n
},
\r\n
{\r\n
\"F1\": 10.0,\r\n
\"F2\": \"abc\",\r\n
\"F3\": \"def\",\r\n
\"F4\": \"asd\",\r\n
\"F5\": \"998907\"\r\n
}
]
}
I could see similar question jqgrid not showing data, i've checked it and i did not get rid of my problem though
Why is the json data not appended ? How do i do it ?
Edit
as part of the answer, i've removed my javascript to call the jqGrid and replaced the code for it as posted in the answer by oleg.
Also i've made little changes to the code in the server side.
Here is what the server side code is:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static string GetCompanyList()
{
var data = GetAllData();
//string response = JsonConvert.SerializeObject(data, Formatting.Indented);
return data;
}
public static string GetAllData()
{
try
{
//Grab the connection string defined in web.config
var connectionString = ConfigurationManager.ConnectionStrings["Test_3ConnectionString"].ConnectionString;
DataTable dt = null;
//Command Text
string commandText = "SELECT * FROM EmpDetails";
dt = SQLHelper.ExecuteDataTable(connectionString, CommandType.Text, commandText, "EmpDetails");
string result = JsonConvert.SerializeObject(dt);
return result;
}
catch (Exception ex)
{
throw;
}
}
Things going weird hour by hour. When i run my application i've the following grid.
I only have 9 rows in my table and it is displaying viewing 1-10 of 552.
Can someone please help me what is wrong with the serialization
There are may errors in your code. It looks like you used some retro code example which is at least 3 years old.
The main error in the server code is usage of JsonConvert.SerializeObject inside of web method. If you defines ResponseFormat=ResponseFormat.Json then the method should return object of any type and not string. .Net convert the object automatically to JSON. So the type of return value of GetCompanyList() should be the same as the return type of GetAllData(). After the changes the web method should returns the data like
{
"d": [
{
"F1": 1,
"F2": "Name",
"F3": "Address",
"F4": "City",
"F5": "Phone"
},
{
"F1": 10,
"F2": "abc",
"F3": "def",
"F4": "asd",
"F5": "998907"
}
]
}
The second problem that you use datatype defined as function. It's low-level way which you should never use if you can get the data with respect jQuery.ajax with some parameters. jqGrid provide a lot of different customization way to change parameters of jQuery.ajax used by jqGrid internally. Typically it's enough to specify the options like
url: "jqGrid_pureJS.aspx/GetCompanyList",
mtype: 'POST',
datatype: 'json',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
repeatitems: false,
root: function (obj) { return obj.d; }
},
gridview: true,
height: "auto",
loadonce: true
It's important additionally to remove all index properties from colModel. The usage of index other as name follows to errors if you use loadonce: true option.
If F1 column contains unique values then I recommend you to add key: true property to the definition of the column "F1".
The results of the changes should be like on the demo:

parsing json response to C# object using jquery

I have following JSON returned from my WCF service:
`{"DoWorkResult":[{"AAID":0,"AreaID":1,"AreaName":"Basement","AssemblyAssessmentID":1,"AssemblyID":493,"AssemblyName":"Handrail (Steel)","AssessmentID":1,"AssessmentName":"University Of WA","AttributesCount":1,"CapitalReplacementUnitCost":623,"CategoryID":7,"CategoryName":"Furniture and Fixtures","CountedUnits":7,"CreatedBy":"Admin","ElementID":37,"ElementName":"Handrails and Balustrades","FacilityID":1,"FacilityName":"Central Chilled Water Plant","FacilityPercentage":"0","IsCompleted":1,"IsHeritage":false,"IsSafetyRisk":false,"Level1Units":0,"Level2Units":0,"Level3Units":0,"Level4Units":0,"Level5Units":7,"MesurementUnit":"Items","PhotosCount":1,"RepairCost":0,"RepairNotes":"","RequiresSpecialist":false,"SiteName":"CRAWLEY","SpaceID":1,"SpaceName":"B01","TasksCount":0}]}
My service method is like this
[System.ServiceModel.OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public List<BLL.BLL_AssemblyAssessment> DoWork(string id) {
return BLL.BLL_AssemblyAssessment.GetAssessemblyAssessmentByAssemblyAssessmentID(1, 1);
}
and I need data parsed in jquery ajax success. how can i parse it to object of my class:
$.ajax({
type: "POST",
url: "MyTestService.svc/DoWork",
data: '{"id":"3"}',
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (msg) {
// $("#errorDiv").text(msg);
alert(msg);
}
});
}
Use
alert(JSON.parse(jsonString));
In your javascript code, calling the $.ajax function with the dataType: "json" option lets jQuery take care of the parsing.
The data variable in the success callback is already a javascript object.
You can access its properties :
success: function(data) {
var html = "",
rows = data.DoWorkResult,
lgth = rows.length,
i, row;
for ( i=0; i<lgth; i++ ){
row = rows[i];
html += "<tr><td>"+row.AAID+"</td><td>"+row.AreaName+"</td></tr>";
// or whatever
}
$("#myTable").html( html );
}
From what I understand, the class BLL.BLL_AssemblyAssessment is a C# class, to be used on the server side, not a javascript class on the client side. In javascript, objects don't need a class definition to hold data.
You can output an object to the console to check its structure :
success: function(data) {
console.log(data);
console.log(data.DoWorkResult);
console.log(data.DoWorkResult[0]);
}
I don't really see the problem.
Since you have specified JSON as the datatype, the JSON is parsed in to a javascript object in the success handler. Just iterate over it using $.each:
//data.DoWorkResult is an array with one element
$.each(data.DoWorkResult, function(k, v){
alert(v.AAID); //will alert 0 one time since there is only one object in the
//array and the value is 0 on the AAID property
});
Fiddle
Note that I need to parse the JSON in my example, since it isnt automatically done by any ajax method there.

Unable to get correct posted data from AJAX call in asp.net handler

I am calling a handler through a AJAX call .
code
var PostData = {"MyName": myName };
$_.ajax(
{
type: "POST",
async: true,
url: 'SomeGenericHandler.ashx',
data: JSON.stringify(PostData),
success: function (msg)
{
var ObjJson = eval(msg);
},
error: function (msg)
{
}
});
Inside ProcessRequest ,these values i am getting :
context.Request.Form.Count = 1
context.Request.Form[0] = "{'MyName':'dave'}"
context.Request.Form["MyName"] = null
How can get the posted data as :
context.Request.Form["MyName"] = "dave"
Thanks in advance :)
You need to send the data in the format of the post as:
$_.ajax(
{
type: "POST",
async: true,
url: 'SomeGenericHandler.ashx',
data: 'MyName=dave&MoreData=SecondName',
success: function (msg)
{
var ObjJson = eval(msg);
},
error: function (msg)
{
}
});
Also take a look at the encodeURIComponent, you may need to encode the parameters :
Combining two Javascript and jQuery scripts

pass an array in jquery via ajax to a c# webmethod

I'd like to pass an array to a c# webmethod but don't have a good example to follow. Thanks for any assistance.
Here is what I have so far:
My array:
$(".jobRole").each(function (index) {
var jobRoleIndex = index;
var jobRoleID = $(this).attr('id');
var jobRoleName = $(this).text();
var roleInfo = {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
};
queryStr = { "roleInfo": roleInfo };
jobRoleArray.push(queryStr);
});
My ajax code
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: jobRoleArray,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
Not sure on the webmethod but here is what I'm thinking:
[WebMethod]
public static bool save_Role(String jobRoleArray[])
You will be passing an array of:
[
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
},
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
}, ...
]
And in my opinion, it would be easier if you have a class that matches that structure, like this:
public class roleInfo
{
public int roleIndex{get;set;}
public int roleID{get;set;}
public string roleName{get;set;}
}
So that when you call your web method from jQuery, you can do it like this:
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: "{'jobRoleArray':"+JSON.stringify(jobRoleArray)+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
And in your web method, you can receive List<roleInfo> in this way:
[WebMethod]
public static bool save_Role(List<roleInfo> jobRoleArray)
{
}
If you try this, please let me know. Above code was not tested in any way so there might be errors but I think this is a good and very clean approach.
I have implement something like this before which is passing an array to web method. Hope this will get you some ideas in solving your problem. My javascript code is as below:-
function PostAccountLists() {
var accountLists = new Array();
$("#participantLists input[id*='chkPresents']:checked").each(function () {
accountLists.push($(this).val());
});
var instanceId = $('#<%= hfInstanceId.ClientID %>').val();
$.ajax({
type: "POST",
url: "/_layouts/TrainingAdministration/SubscriberLists.aspx/SignOff",
data: "{'participantLists': '" + accountLists + "', insId : '" + instanceId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
}
In the code behind page (the web method)
[WebMethod]
public static void SignOff(object participantLists, string insId)
{
//subscription row id's
string[] a = participantLists.ToString().Split(',');
List<int> subIds = a.Select(x => int.Parse(x)).ToList<int>();
int instanceId = Convert.ToInt32(insId);
The thing to notice here is in the web method, the parameters that will receive the array from the ajax call is of type object.
Hope this helps.
EDIT:-
according to your web method, you are expecting a value of type boolean. Here how to get it when the ajax call is success
function AjaxSucceeded(result) {
var res = result.d;
if (res != null && res === true) {
alert("succesfully posted data");
}
}
Hope this helps
Adding this for the ones, like MdeVera, that looking for clean way to send array as parameter. You can find the answer in Icarus answer. I just wanted to make it clear:
JSON.stringify(<your array cames here>)
for example, if you would like to call a web page with array as parameter you can use the following approach:
"<URL>?<Parameter name>=" + JSON.stringify(<your array>)

Resources