Using Webservice to call external Json file using ajax call - asp.net

I have a Json file and an ajax call in Javascript file. Trying to write correct webservice method using Hello World asmx file template. What should I write in method in order to make it display/return/read json data on website?
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:56537/WebService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function (Result) {
debugger;
Result = Result.d;
var data = [];
var dataResource = response

Thats is the solution that worked for me:
[WebMethod]
public string HelloWorld() {
using (StreamReader r = new StreamReader(#"C:\Users\data.json"))
{
string json = r.ReadToEnd();
return json;
}

Related

call a static method in User Control from js or ajax

I am trying to call a static method in User Control from js or ajax.
It is possible to do this if the code method lies directly in WebForm but it is not possible to do it if we put the code method in UserControl and then put this UserControl in a WebForm.
Code Behind:
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static string GetNameFromCodeBehind (string name)
{
return "Hello from Code-Behind, " + name ;
}
AJAX Code:
$.ajax({
type: "POST",
url: "MyUserControl.ascx/GetNameFromCodeBehind",
data: JSON.stringify({ name: "Anton" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: true,
success: function (data) {
alert(data.d);
},
error: function (e) {
alert(e.statusText)
}
});
Ajax Error:
Not Found
If GetNameFromCodeBehind is inside MyUserControl.ascx, then it will be able to find a URL. Moreover, you have written the name of static method as callFromCodeBehind. So, you need to write the URL sccordingly

Json PaserError when calling web service

I am getting this "Json ParserError" in chrome console when looping through the response returned by web service. I am using dataType: jsonp as i am trying to call cross domain ajax call in development environment, BUT stuck with this error.
$.ajax
function callajax1() {
$.ajax({
url: "http://www.sample.com/Integration/PhotoCompetitionHelper.asmx/SayHello",
data: "",
dataType: 'jsonp',
type: 'POST',
contentType: "application/json; charset=utf-8",
jsonpCallback: 'showResult',
success: function (data) {
console.log(data.d)
},
error: function (data, status) {
console.log("FAILED:" + status);
}
});
}
function showResult(data) {
console.log(data.d);
}
WebService
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SayHello()
{
return "Hello";
}
JSON Response
{"d":"Hello"}
ERROR
FAILED:parsererror
You are getting the parser error because when your dataType is jsonp, it expects a script and not json. Try to include a callback function.

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.

converting object variable to json string for asp.net page method

This is probably a very simple task to perform but I'm taking the risk to ask anyway.
I have an object variable that looks like this:
var MyObj = {"Param1": "Default",
"Param2": "test",
"Param3": 3 };
I'm using ASP.net and I'm looking to pass this object to a page method via jquery.
So far, I have this javascript code:
function LoadObject () {
var TheObject = MyObj.toString();
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: TheObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
I have a page method set up in the .cs file and I put a breakpoint in it but it never gets there; nothing happens.
Please let me know what changes I need to make to get this to work.
Thanks.
You need to serialize TheObject into a JSON string, and ensure that the GetCount method accepts an object with the same signature as TheObject.
I use the jQuery.JSON library to do this so that my syntax becomes:
data: "{ methodParameterName: " + $.toJSON(TheObject) + " }"
I use this library, but you can acheive the same thing with any other library in a similar manner
The first thing that you need to know is that you need to match your method name with your url
for example if your method on your code behind is named "calculate", your url must be something like this "../Pages/TestPage.aspx/calculate"
other thing that you need to keep in mind is the parameters of your method, the names and the types of your parameters must match in you ajax call and your method (code behind)
if the sign of your method is something like this
[WebMethod]
public void Calculate(string data){
// your code here
}
Your ajax call must be like this:
function LoadObject () {
var objetoJson = {
data: JSON.stringify(MyObj)
};
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/Calculate",
data: objetoJson ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
This section is so important:
var objetoJson = {
data: JSON.stringify(MyObj)
};
the name "data" is the name of your parameter in your method (code behind) and "JSON.stringify" is a helper functions already defined on your browser to convert and object to string
Hope this helps
Take a look at this thread: JSON stringify missing from jQuery 1.4.1?
Abstract: jQuery doesn't have a native method to do it. But there are many plugins out there.
EDIT
Sample C# code receiving your JSON object:
[WebMethod]
public static int GetCount(GetCountParams p)
{
// ... Do something with p.Param1, p.Param2, etc.
return 0;
}
public class GetCountParams
{
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
EDIT 2
Sample jQuery AJAX call using that object as parameter:
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: "{ p: '" JSON.stringify(MyObj) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json"
});

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},

Resources