Calling ASP.NET web service function via GET method with jQuery - asp.net

I'm trying to call web service function via GET method using jQuery, but having a problem. This is a web service code:
[WebService(Namespace = "http://something.com/samples")]
[ScriptService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestWebService : System.Web.Services.WebService {
[WebMethod]
public string Test2()
{
string result = null;
try
{
result = "{'result':'success', 'datetime':'" + DateTime.Now.ToString() + "'";
}
catch (Exception ex)
{
result = "Something wrong happened";
}
return result;
}
}
That's the way I call the function:
$.ajax({ type: "GET",
url: "http://localhost/testwebsite/TestWebService.asmx/Test2",
data: "{}",
contentType: "application/json",
dataType: "json",
error: function (xhr, status, error) {
alert(xhr.responseText);
},
success: function (msg) {
alert('Call was successful!');
}
});
Method is called successfully, but result string gets covered by XML tags, like this:
<string>
{'result':'success', 'datetime':'4/26/2010 12:11:18 PM'
</string>
And I get an error because of this (error handler is called). Does anybody know what can be done about this?

Enable ASP.NET ASMX web service for HTTP POST / GET requests
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string Test2()
{
[...]
}

Rule for json:
You can only access data from the same domain!
The only exception is when using jsonp (which is quite complicated to implement since there is no jsonp serializer in the .NET framework).
If your are using a standard web service (and not WCF) you can find guidance howto implement this here.

Make sure to add this to your ajax options:
contentType: "application/json; charset=utf-8"
Your overall request should look like this to get json back instead of XML:
$.ajax({ type: "GET",
url: "http://localhost/testwebsite/TestWebService.asmx/Test2",
data: "{}",
contentType: "application/json",
dataType: "json",
contentType: "application/json; charset=utf-8".
error: function (xhr, status, error) {
alert(xhr.responseText);
},
success: function (msg) {
alert('Call was successful!');
}
});
ScottGu has a full breakdown on what's required here, but it looks like the missing contentType in your case (that one drove me nuts for a while too).

You might try setting the ResponseFormat on your methods. See http://williamsportwebdeveloper.com/cgi/wp/?p=494 to see how they did it for JSON. It probably just defaults to XML.

You need to decorate the method with the ScriptMethodAttribute:
[WebService(Namespace = "http://something.com/samples")]
[ScriptService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestWebService : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod]
public string Test2()
{
[...]
}
}
This will ensure that the method returns JSON by default (the default value of ResponseFormat is Json).

Did you try WebInvokeAttribute, it has members that define Request & Response formats where you can set to WebMessageFormat.Json.
Something like:
[WebInvoke(UriTemplate = "ServiceName", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,
Method = "POST")]

You can use http handler instead of
web service.
You can parse xml response with
javascript on the client.

Related

Action page in asp.net

How do i create a page like an action page in php, in C# ?To be specific I only require a page that contains only methods that handle various operations and return result.
How do i solve the above scenario ?
Create a class, then inside the class create your methods to construct the logic behind your application.
Then reference this class with the using keyword in your web pages and use the methods you created wherever you like.
Read about HttpHandlers.
For example, you want to have a method that returns a json string in a web forms application.
Add a new item to your project of type "Generic Handler". This will create a new .ashx file. The main method of any class that implements IHttpHandler is ProcessRequest.
public void ProcessRequest (HttpContext context) {
if(String.IsNullOrEmpty(context.Request["day"]))
{
context.Response.End();
}
string json = "";
byte[] bytes = getByteArray();
json = JsonConvert.SerializeObject(bytes);
context.Response.ContentType = "text/json";
context.Response.Write(json);
}
Change the url in your AJAX call and that should do it. The JavaScript would look like this , where GetFileHandler.ashx is the name of the IHttpHandler you just created:
$.ajax(
{
type: "POST",
async: true,
url: 'Handlers/GetFileHandler.ashx',
data: "Day=" + $.toJSON(day),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SUCCESS:" + msg);
},
error: function (msg) {
console.log("error:" + msg);
}
});
Read more here for more details.

how to pass a XML parameter to a WEB METHOD using jQuery Ajax

I have a web method that can accept a XElement argument and I want to call it using jQuery Ajax. I can call simple methods using jQuery Ajax with simple argumnets(such as int,string,...), but I don't know how pass to a complex type using jQuery Ajax.
Edit 1)
I have a simple web service :
[WebMethod]
public bool MyGetPassXML(System.Xml.XmlDocument nima)
{
try
{
if (nima == null )
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
For the call I've written this code:
var xmlFragment = 'AB';
$("#Button2").click(function() {
$("#Loader").show();
$.ajax({
type: "POST",
url: "WebService.asmx/MyGetPassXML",
data: "{'nima':'" + xmlFragment + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
$("#Loader").hide();
alert('OK');
}
});
});
I've test it with Firefox and see request an response with FireBug but I get this error:
{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Xml.XmlDocument\u0027","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary2 rawParams)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
I change System.Xml.XmlDocument to XElement but again I get this error. How can I solve this?
Instead of XmlDocument as the web method argument type, I would change it to a string. You can create an XmlDocument from a string by calling .LoadXml(nima).
Edit to answer the request for an example:
Let's say you had a simple class like the following (forgive my c#):
public TestClass {
public string Var1 { get; set; }
public string Var2 { get; set; }
public string void TestClass()
{
}
}
And a web method like the following:
[WebMethod]
public bool MyGetPassJSON(TestClass nima)
{
// do something
}
And your javascript / jquery could look like the following:
$.ajax({
type: "POST",
url: "WebService.asmx/MyGetPassJSON",
data: "{nima: {Var1:'something',Var2:'something else'}}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
$("#Loader").hide();
alert('OK');
}
});
In your case, you could have:
"cities": ["A", "B","C","D"]
This is a very simple example, but much more complex parameters are possible. You can also build up your json as a proper javascript object and use JSON.stringify to send it to your web method.
Construct your XML as a javascript variable and pass that variable as your data into your AJAX call.
var xmlFragment = '<complexType><simple attributeEx="attributeA">A</simple><simple attributeEx="attributeB">B</simple></complexType>';
See http://www.w3schools.com/xml/default.asp for more information on XML.
What you pass in xmlFragment might not be a correct XML because there is no XML declaration.
Also - If you didn't state that anywhere, I don't think your method consumes JSON
I am not familiar with your server side technology, but if you want to send XML type content there is no way to state it in JSON. You have to send stuff like this:
$.ajax({
type: "POST",
url: "WebService.asmx/MyGetPassXML",
data: xmlFragment,
contentType: "application/xml; charset=utf-8", //not sure if charset should be there for xml
dataType: "json", //data type expected in _RESULT_. I have no idea what your method returns
success: function(result) {
$("#Loader").hide();
alert('OK');
}
});
And you might have to change something about your method to receive the whole XML. But this is the only commonly avaliable way to send anything to the server with any indication of XML object type.

ASP.NET - Call Web Service From User Control ( .Ascx ) Returns Error 500 Internal Server Error

so I have some problem. The Problem's Goal is that, when i try to call Web Service from User Control with Ajax, I got 500 Internal Server Error.
There is my code sample:
Web Service .CS
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class BudgetJson : System.Web.Services.WebService {
public BudgetJson ()
{
}
[WebMethod]
public static String GetRecordJson()
{
return " Hello Master, I'm Json Data ";
}
}
User Control ( .Ascx ) File ( Ajax Call )
$(document).ready(function () {
$.ajax({
type: "POST",
url: "BudgetJson.asmx",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
alert(msg);
}
});
});
So, when page loads and request is sent, I got such response:
soap:ReceiverSystem.Web.Services.Protocols.SoapException: Server was
unable to process request. ---> System.Xml.XmlException: Data at
the root level is invalid. Line 1, position 1. at
System.Xml.XmlTextReaderImpl.Throw(Exception e) at
System.Xml.XmlTextReaderImpl.Throw(String res, String arg) at
System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() at
System.Xml.XmlTextReaderImpl.ParseDocumentContent() at
System.Xml.XmlTextReaderImpl.Read() at
System.Xml.XmlTextReader.Read() at
System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent() at
System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at
System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at
System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at
System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage
message) at
System.Web.Services.Protocols.SoapServerProtocol.Initialize() at
System.Web.Services.Protocols.ServerProtocol.SetContext(Type type,
HttpContext context, HttpRequest request, HttpResponse response) at
System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type,
HttpContext context, HttpRequest request, HttpResponse response,
Boolean& abortProcessing) --- End of inner exception stack
trace ---
If i will add method name to url, I got such error:
Unknown web method GetRecordJson. Parameter name: methodName
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unknown web method
GetRecordJson. Parameter name: methodName
Any Solution ?
A couple things on the server-side:
The method should not be static. That's only the case for "page methods" on ASPX pages.
Second, you need to decorate the service class with the [ScriptService] attribute to be able to communicate with it in JSON, which I'm assuming you probably want to do since you're using jQuery.
[ScriptService]
public class BudgetJson : System.Web.Services.WebService {
[WebMethod]
public String GetRecordJson()
{
return " Hello Master, I'm Json Data ";
}
}
On the client-side, you need to specify which method you want to execute in your $.ajax() URL:
$.ajax({
type: "POST",
url: "BudgetJson.asmx/GetRecordJson",
data: "{}",
// The charset and dataType aren't necessary.
contentType: "application/json",
success: function (msg) {
alert(msg);
}
});
You can also simplify the $.ajax() usage a bit, as shown above. The charset isn't necessary and jQuery automatically detects the dataType from the headers sent back from the server.

Can you help me to find out why my $.ajax call to HelloWorld webservice fails here?

I am trying my best but cannot figure out why I do not get a sucesful response to such a simple web service; can you have a look at it tell me what do I miss, pls?
Each time only the error function is called and Fiddler says I have HTTP Response 500.
thanks!
Additional Notes:
I checked Fiddler and it says:
No web service found at: /JQuery-Recepie/Chapter16-Ajax/MyWebService.asmx. But WHY?!?
My WebService class:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService {
public MyWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
My JavaScript that is bound to a button's click event which calls the webservice:
function jqHelloCall(){
$.ajax({ type: "POST",
contentType: "application/json; charset=utf-8",
url: "MyWebService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg){
alert(msg==null);
alert(msg.d);
},
error: function(){
alert('error');
}
}); }
Use the Firebug in Firefox to see the response sent by IIS. In Firebug on the Net tab you can filter only the Ajax requests (XHR). Most certainly you will find all the details about server exception in the response body IIS will send back.
pencilCake : I checked Fiddler and it says: No web service found at: /JQuery-Recepie/Chapter16-Ajax/MyWebService.asmx. But WHY?!?
Because the web methods should be STATIC
[WebMethod]
public static string HelloWorld() {
return "Hello World";
}
add the scriptMethod attribute to your service method...
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
return "Hello World";
}

Escaped JSON response with [WebMethod]

The JSON response from the following code is wrongly escaped as described below.
My webmethod is like this:
[WebMethod (Description="doc here")]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string responseMyObject() {
if (!Setup()) return "";
...
Proxy pu = new Proxy(...);
...
string toReturn = JavaScriptConvert.SerializeObject(pu.getMyObject());
Console.WriteLine(toReturn);
return toReturn;
}
from the console I get:
{"field1":vaule1,"field2":value2}
from JS:
$.ajax({
type: "POST",
url: "/myapi/myClass.asmx/responseMyObject",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var object = msg.d;
alert(object.field1);
}
});
The problem is that in the HTTP response header I can see that the JSON response is wrongly (?) escaped in the following way:
{"d":"{\"field1\":value1,\"field2\":value2}"}
What's strange is that the console print is fine (but not yet encapsulated in {d: ...}
{"field1":value1,"field2":value2}
With similar code, if I call a [WebMethod] that returns basic types (no object) the JSON response is ok. Like:
{"d":8080}
[WebService]
[ScriptService]
public class MyWebService : WebService
{
[WebMethod (Description="doc here")]
[ScriptMethod( UseHttpGet=false, ResponseFormat=ResponseFormat.Json)]
public MyObjectType responseMyObject()
{
Proxy pu = new Proxy(...);
return pu.GetMyObject();
}
}
You dont need a JSON serializer, tagging it with the ScriptService attribute gives it tie ability to serialize JSON out. You were pre serializing the JSON and then serializing it again :(
Why are you calling JavaScriptConvert.SerializeObject?
Can't you just change the return type of your method to be the type returned by pu.getMyObject() and the framework will do the rest?
In other words...
[WebMethod (Description="doc here")]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public MyObjectType responseMyObject()
{
Proxy pu = new Proxy(...);
...
return pu.GetMyObject();
}
At the moment I think you're serializing your object into a JSON format and then, when you return from the method, the framework is serializing that string (which contains JSON formatted data) into a JSON format.

Resources