parsing json response to C# object using jquery - asp.net

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.

Related

WebMethod access page control and set value

My page name
public partial class AtamaGorevDegistir : System.Web.UI.Page
{}
My webmethod ajax side
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});
My webmethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
AtamaGorevDegistir atama = new AtamaGorevDegistir();
atama.AtananSuren.Value = "123";
return null;
}
But my problem my Control is null . But i can access this method but didnt set value and give error message. Why this happened?
WebMethod and ScriptMethod can't access the controls collection of the calling page. Think of it as outside the normal Web Forms lifecycle. When you use AJAX, you need to pass all data to the server side method it needs, and your server side should return all data that the client side needs. Then the client side should take that returned data and manipulate the DOM as necessary to display the result.
In your WebMethod, return the data instead of trying to assign it to a control, remove the return null;.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
return "123";
}
In your client side success handler, get the returned data and set the value of the control using JavaScript.
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
//set control value to data.d here
}
});
You don't set the control value with a webmethod. Your return a value and from the api and do something with it, in the browser. Working with webmethods are not like webforms. The value you return in your webmethod is null... you're setting that null value into 'dd' in js, but you don't do anything with it. When you get your value back from the webmethod you need to do something with it. try 'alert(data.d)' in your success callback to see what i mean. Then $('#elm').text(data.d) if you want it on the page.
You should add parameters to data.
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
data:JSON.stringify({ KayitID: '1', TeklifID:'2' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});

jqgrid form editing editoptions select ajax add parameter

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;
...

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>)

2 page methods on an aspx page

I'm calling a page method with jquery and it works just fine. I'm creating a second one and it's not working at all; all I get is the error function. Is it possible to put more than 1 page method in an aspx page?
Here's my jquery on the client:
function LoadCount() {
var TheObject = $.toJSON(CurrentForm);
var TheParameter = "{'TheParameter' : '" + TheObject + "'}";
$('#testobj').html("loading");
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetCount",
data: TheParameter,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
function successFn(thedata) { $('#result').html(thedata.d); };
function errorFn() { alert("problem getting count"); };
function LoadData() {
var ConfirmLoad = "test";
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetLoaded",
data: ConfirmLoad,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successLoad,
error: errorLoad
});
};
function successLoad(thedata) { alert((thedata.d)); };
function errorLoad() { alert("problem getting loaded"); };
And on the server side, I have this:
[WebMethod]
public static string GetCount(string TheParameter)
{
// some code
return JsonResult;
}
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
return "test string";
}
LoadCount and GetCount work great, I thought I'd copy the implementation to create another page method but the second time, nothing good happens. Thanks for your suggestions.
You need to set dataType: "text" in the $.ajax() call properties if you're just returning plain text instead of a JSON encoded string.
You might also want to leave the contentType unspecified (at the default value of 'application/x-www-form-urlencoded') if your're sending plain text instead of a JS object.

Adding JSON results to a drop down list with JQUERY

I'm making a call to a page method via AJAX in my ASP.NET application via JQUERY's AJAX method e.g.
$.ajax({
type: "POST",
url: "page.aspx/GetDropDowns",
data: "{'aId':'1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function() {
alert('Error getting page');
}
I'll be returning the results in JSON format, whereby I will be populating a drop down. I could do this part myself but I want to know if there is any built in magic in JQuery for processing JSON results or if there are any good utility scripts for this sort of thing.
There is little jQuery itself can help you with populating dropdown. You just need to create HTML and append it to your dropdown.
I'm not sure what is the format of your data so I'm assuming it's an object where keys should be dropdown's keys and values should be dropdown's values.
I also prefer using $.post then $.ajax as it has a clearer structure for me.
$.post('page.aspx/GetDropDowns', {'aId': '1'}, function (data, status) {
if (status === 'success') {
var options = [];
for (var key in data) {
options.push('<option value="' + key + '">' + data[key] + '</option>');
}
$('#yourId').append(options.join(''));
} else {
alert('error');
}
}, 'json');
In the past I have used a plugin when working with dropdowns.
http://www.texotela.co.uk/code/jquery/select
Request the JSON data:
//Get the JSON Data
$.getJSON(url, function(json) {
PopulateDropDownFromJson(json, "#element");
});
and then just pass the JSON into a function that uses the plugin above
function PopulateDropDownFromJson(json, element){
$.each(json, function() {
$(element).addOption(this[valueText], this[displayText], false);
});
}

Resources