JSON format using $.ajax and C# - javascript

If I use $.ajax JQuery and I call WebMethod, I get JSON:
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify({ id: idX, id2: idY }),
async: true,
cache: false,
url: "/ws/Courses.asmx/GetCourses",
contentType: "application/json; charset=utf-8",
success: function (data) {
RenderCourses(data.d);
},
});
but JSON has "d" property.
function RenderCourses(data) {
if (data.d.length > 0) {
If I use json = JsonConvert.SerializeObject in C#, hasn't the "d" property.
string script = "var data = " + json + "; RenderCourses(data);";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "dataVar", script, true);
And RenderCourses fails.
Any reasons?

ADO.NET WebMethods always serialize the response like this. d meand "data". And you can't do anything with this.
JsonConvert.SerializeObject is a method from third party software (Newtonsoft). It just simple serialize your object to JSON.

Related

How can I send files along with other field's data to webmethod is asp.net using jquery ajax call?

I have a webform which has x number of textboxes and y number of dropdowns etc
I am using this code to send data to webmethod at the server:
$.ajax({
type: "POST",
url: "SupplierMaster.aspx/RegisterSupplier",
data: JSON.stringify({
id: $('#txtbidderid').val(),
bidamt: $('#txtbidamt').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
Now the problem is that I also want to include file attachments on this form.
How do I add the files to data: of $.ajax method?
I do not want to use external plugins etc unless absolutely necessary.
Lets say I modify my data object to look like this :
var dataToSend = {};
dataToSend.id = $('#txtbidderid').val()
dataToSend.bidamt = $('#txtbidamt').val()
dataToSend.append( 'file', input.files[0] );
What would the webmethod armument look like?
For example lets suppose it looks like this as of now:
[WebMethod] public static string SubmitBid(string id, string bidamt.....)
You can try something like this. You may need to manipulate content type.
var dataToSend = new FormData();
dataToSend.append( 'file', input.files[0] );
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
data: dataToSend,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
You cannot send file as application/json; charset=utf-8 to the server and so i suggest you to use application/x-www-form-urlencoded as contentType and also data as FormData as below.
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
type: 'POST',
data: new FormData(formElement),//Give your form element here
contentType: false,
processData: false,
success: function () {
//do success
}
});

Ajax call not accepting Names with apostrophe as a parameter

$(".loadingPnl").removeClass('hdn');
var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/SaveAvailableFavoriteItem";
var linkName = $('.txtLinkName').val();
linkName = linkName.replace("'","\'");
$.ajax({
type: "POST",
url: callUrl,
data: "{'linkName': '" + linkName + "', 'webSiteUrl':'" + $('.txtWebAddress').val() + "','iconId':'" + $(".ddlIcons").val() + "'}",
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});
return true;
}
The problem is you're building JSON yourself as the request parameters. Moreover, you're building invalid JSON (JSON property names are always with double quotes (")).
Instead, pass an object and let jQuery take care of how to send it - if you pass that instead of a string the server can figure it out. If you really want to do it yourself you can also pass an object to JSON.stringify.
var payload = {
linkName: linkName,
webSiteUrl: $('.txtWebAddress').val(),
iconId: $(".ddlIcons").val()
};
$.ajax({
type: "POST",
url: callUrl,
data: JSON.stringify(payload), // or just payload
contentType: "application/json; charset=utf-8",
processData: false, // if you just pass payload, remove this
dataType: "json"
// you had two `return`s here, but they wouldn't work, make sure
// you understand why
// http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call
});
You can send a JSON instead. Or use JSON.stringify if you want String.
{
'linkName' : linkName,
'webSiteUrl' : $('.txtWebAddress').val(),
'iconId' : $(".ddlIcons").val()
}
Don't create JSON string by yourself AND don't use JSON.stringify().
Problem with creating JSON string yourself is to escape string properly for JavaScript (which could be tricky). see Special Characters
Problem with JSON.stringify is that I found it somehow slower than XMLHttpRequest which is strange because I thought it is using JSON.stringify behind curtains.
XMLHttpRequest is handling this for you. If you just pass your object as a data and XMLHttRequest will do the trick.
$.ajax({
type: "POST",
url: callUrl,
data: {'linkName': linkName,
'webSiteUrl': $('.txtWebAddress').val(),
'iconId': $(".ddlIcons").val()
},
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});

Json Data extraction

I have a webservice and it returns json data like this..
{"d":"{\"RES\":[],\"STAT\":\"FAIL\",\"SID\":\"0\"}"}
how i can i read the STAT=FAIL from this. I wrote service in c#.
my script is
$.ajax({
type: "POST",
url: "http://localhost/EMRDMSService/Service.asmx/User_Login",
data: "{lg:" + JSON.stringify(GetLogDet) + "}",
// url: "http://localhost/EMRDMSService/Service.asmx/Permission_List",
// data: "{userid:" + JSON.stringify(GetLogDet) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
console.log(r.d.STAT);
}
});
But the r.d.STAT is undefined?
Can anybody help me with this?
As said in some of the comments, {"d":"{\"RES\":[],\"STAT\":\"FAIL\",\"SID\":\"0\"}"} isn't correct JSON. However, if you can't update the webservice, you could try this in your success callback:
var d = JSON.parse(r.d);
console.log(d.STAT);
EDIT in response to OP edits r.d.STAT will be undefined because d is interpreted as a String, not a Object. That's why you'll have to parse it or update the webservice to remove the quotes around the value of d.

Parse List of Entities using Json In Javascript + MVC3

I have looked for a solution , but nothing that fits my needs was found on the site, so here goes:
I have a Controller that returns a Json:
return Json(new { Item = searchModule});
searchModule is a list of Profiles:
{ "Item":[{"ProfileID":4854,"NickName":"Johnny","users":null,"FirstName":"John","LastName":"Doe"}]}
In JavaScript we have:
$.ajax({
type: "POST",
url: action/controller,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.Item)
}
})
That returns an object. How can I obtain: Firstname,LastName and NickName ???
Additional answer: If I write the code like below:
var request = $.ajax({
type: "POST",
url: action/controller,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
}).responseText
var obj = json.Parse(request)
, request is null.
since they're objects structured according to the JSON, you should be able to just access the properties like so: data.Item[0].Firstname. You may or may not need to use jQuery.parseJSON to get to this step - calling that is trivial.

How to call ASP.net web method with Array parameter from jQuery Javascript?

I have the following ASP.net web method:
[WebMethod]
public static string SaveUserNew(string id, string[] roles)
{
doStuff(id, roles);
}
I'm calling this code from jQuery Javascript code, but I don't know the syntax for passing an array. Ordinarily, I write jQuery code to call web methods that looks like this:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: '{"foo":"fooValue"}',
contentType: "application/json;",
dataType: "json",
}
Please shed some light on this.
Update: Here is an example of code without arrays that does work:
[WebMethod]
public static string SaveUserNew(string id)
{
return "0";
}
var jdata = '{ "id": "3TWR3"}';
$.ajax({
type: "POST",
url: "UserMgmt.aspx/SaveUserNew",
data: jdata,
contentType: "application/json;",
dataType: "json",
traditional: true
}
});
My intention is to write some code in a similar style where I pass arrays to my web method.
Passing param to webmethod is a little bit tricky. Try this one
[WebMethod]
public static string GetPrompt(string[] name)
{
return "Hello " + name[0] + " and " + name[1];
}
jscript
var param = "{'name':['jack', 'jill']}";
var option = {
error: function(request, status, error) {
alert(error);
},
cache: false,
success: function(data, status) {
alert(data.d);
},
type: "POST",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
url: "../Server/ArrayParam.aspx/GetPrompt"
};
$.ajax(option);
You need to
1) assign the data parameter to have an object with the properties id and roles.
2) assign the roles property an array of strings.
3) Set the traditional setting to true while passing options to ajax call.
e.g:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: {
"id":"1",
"roles":[
"Admin",
"Something",
"Another Thing"
]
},
contentType: "application/json;",
dataType: "json",
traditional: true //#############################
}

Categories