how to handle object passed by jquery on the server - asp.net

I have this Ajax call to an webMethod
$.ajax({
type: "post",
url:"Default.aspx/MessagesCount",
data: ko.toJSON({ tasks: self.tasks }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var msg = $.parseJSON(result.d);
alert(msg.Tasks[0].title)
},
error: function (resultx) { alert(resultx); }
});
the data send is and object with the following values
{"tasks":[{"title":"PRIVMSG001"},{"title":"PRIVMSG002"},{"title":"PRIVMSG003"},{"title":"PRIVMSG004"},{"title":"PRIVMSG005"},{"title":"PRIVMSG006"}]}
The web method is
<WebMethod()> _
Public Shared Function MessagesCount(ByVal tasks As Object) As String
'How to handle tasks object, using it properties, values exc.
'Testing return dum json
Return "{""Tasks"": [{""title"": ""PRIVMSG001""},{""title"": ""PRIVMSG002""},{""title"": ""PRIVMSG003""}]}"
End Function
How to handle the object send by the client on the server, need to be able to use those values and properties.
Thanks

Related

webservice not returning values to on jquery ajax request

I would like consume cross-domain web-service from client with jquery.here is my code
function getId() {
var testid = ($('#<%=PreviousTest.ClientID %> OPTION:selected').val());
jQuery.support.cors = true;
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
}
my webservice returns values in this format
{"Table":[{"minlatency":16.0,"Time":"/Date(1328248782660+0530)/"},{"minlatency":7.0,"Time":"/Date(1328248784677+0530)/"},{"minlatency":13.0,"Time":"/Date(1328248786690+0530)/"},{"minlatency":6.0,"Time":"/Date(1328248788690+0530)/"},{"minlatency":20.0,"Time":"/Date(1328248790707+0530)/"},{"minlatency":12.0,"Time":"/Date(1328248792723+0530)/"},{"minlatency":26.0,"Time":"/Date(1328248794723+0530)/"},{"minlatency":18.0,"Time":"/Date(1328248796723+0530)/"}]}
Calls in cross-domain work in a different way. They create dynamic javascripts that are inserted to the page using a callback function. This function is used to handle the response from the service. The Jquery calls add a "?callback=?" to the URL of the service, where "callback" is the name of the function that will be inserted.
To call cross-domain services with JQuery you have to do the following:
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //The data type that you must use is JSONP. Basically tells JQuery that the request is cross-domain
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
},
jsonpCallback: 'callback' //Dude to the fact that the JS is being generated dynamicaly, this tells JQuery to use the name "callback" for the function that will handle the result, as it adds "?callback=?" to the URL
});
You could also use "jsonp" instead of "jsonpCallback" if you want to "override the callback function name in a jsonp request" (from JQuery).
It worked for me (in WCF REST services which communicate with JSON messages, but it should work the same way in your case). This is all explained in the JQuery Ajax documentation.
Hope this helps.

jQuery + Webservices: Webservice not returning JSON, only XML

Looks like it just doesnt want to work...
# Webservice:
<ScriptMethod(UseHttpGet:=False, ResponseFormat:=ResponseFormat.Json), WebMethod()> _
Public Function LoginDB(ByVal user As String, ByVal pass As String) As String
global.user = user
global.pass = pass
If (<<lots of code to check if user is valid>>) Then
Return "1"
Else
Return "0"
End If
End Function
The webservice DOES work, if the user is valid, returns 1 otherwise 0. But I always get it as XML
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">"0"</string>
#Jquery:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Services/Autenticacao.asmx/LoginDB",
data: "{'user':'ale','pass':'123'}",
dataType: "json",
success: function(data) {
alert(data);
},
.....
Anyone?
You need to post your jQuery, but are you using the getJson jQuery method? If not you need to explicitly set the correct data type:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/WebMethodName",
data: "{}",
dataType: "json"
});
Or use the getJSON method:
$.getJSON('WebService.asmx/WebMethodName', function(data) {
//Do something with JSON response (data)
});
If you want your webservice to return JSON
asked and answered... How to return JSON from a 2.0 asmx web service

Novice with jQuery AJAX

I am simply learing Ajax with jQuery and have a simple page method that takes in a parameter and returns a string. For some reason, I am not getting the return string but I am getting to my 'success' message:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "testFormMatt.aspx/sayHello",
contentType: "application/json; charset=utf-8",
data: '{"name": "matt"}',
dataType: "json",
success: function(msg) {
$.jGrowl('The web service has been successfully called');
$('#result').append(msg);
}
});
});
When you call append, you need to specify the property of the JSON object that you want to append.
So if your page is returning:
{ message: "Hello, Matt" }
Then you'd need to call append like this:
$("#result").append(msg.message);
If your page is not returning JSON, then you need to take the dataType: "json" out of the $.ajax call. The dataType parameter is for specifying the expected data type of the response, not the data type of the request.

Whats the best way to send array of objects from javascript to webservice?

I have in my javascript these 2 functions "classes":
// product class
function Product() {
this.id;
this.qty;
this.size;
this.option;
}
// room class
function Room() {
this.id;
this.type;
this.products = [];
}
I have my js logic which fills rooms and their products.
Now i want to send array of rooms to a webservice to do some calculations and get back from it the result.
How to send this array objects to the service and whats the data type which the service will receive to loop through and process?
I tried to write the javascript code like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "_Services/MyWebService.asmx/CalculatePrices",
data: "{'rooms':'" + roomsObjects + "'}",
dataType: "json",
success: function(result) {
alert(result.d);
}
});
And the webservice like this:
[WebMethod]
public string CalculatePrices(object rooms)
{
return "blabla";
}
but i find that rooms in the wbservice is always = [object Object]
For that case this would work:
//...
data : '{"rooms":[' + roomsObjects.join() + ']}',
//...
The above code will generate a valid JSON string, but I recommend you to get a JSON library and use JSON.stringify function:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "_Services/MyWebService.asmx/CalculatePrices",
data: JSON.stringify({'rooms': roomsObjects}),
dataType: "json",
success: function(result) {
alert(result.d);
}
});
If you don't mind including a tiny JavaScript library, I think using json2.js' JSON.Stringify is the best way to serialize objects for use with ASP.NET AJAX services.
Here's a snippet from that post:
// Initialize the object, before adding data to it.
// { } is declarative shorthand for new Object().
var NewPerson = { };
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewPerson' : NewPerson };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PersonService.asmx/AddPerson",
data: JSON.stringify(DTO),
dataType: "json"
});
There's no array in that example, but JSON.Stringify does serialize JavaScript arrays in the correct format to send in to ASP.NET AJAX services for array and List parameters.
A nice thing about using JSON.Stringify is that in browser that support native JSON serializing (FF 3.5, IE 8, nightly builds of Safari and Chrome), it will automatically take advantage of the browser-native routines instead of using JavaScript. So, it gets an automatic speed boost in those browsers.
Change:
data: "{'rooms':'" + roomsObjects + "'}",
to:
data: {'rooms':roomsObjects},

calling a webservice with jquery that accepts five STRING params?

is it possible to call a webservice that accepts 5 string parameters without sending via json? (is this recommended) I have created a webservice with a method that accepts 5 string params.. and i have my jquery
$.ajax({
type: "POST",
url: "Service.aspx/CreateClient",
data: "{}",
contentType: "application/json; charset=utf-8", //// ERMMM ???
dataType: "json", // ERMMM?
success: function(msg) {
alert(msg.d);
},
error: function() {
alert('error');
}
});
The old way without using jquery was to do this
this.para.add("Name", name);
this.para.add("ClientNum", clnum);
this.para.add("Email", email);
this.para.add("Register", register);
this.para.add("Message", message);
SOAPClient.invoke(this.url, "MyService.aspx/CreateClient", this.para, true, this.completeDone, this);
At the other end it lands and fills in all parameters....
What is the recommended way?
why not use querystring variables and avoid the overhead of the SOAP protocol?

Resources