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(IDictionary
2 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#):
And a web method like the following:
And your javascript / jquery could look like the following:
In your case, you could have:
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.