0

I am using a web method and ajax call but can't get it right with parameters?

I have worked though a number of fixings but non have been able to solve my problem?

I need to pass though a string and have my web method return a data table, why is it necessary to pass it through as a json?

Here is the ajax call:

var jsdata = '{category:' + category + '}';
var jstext = JSON.stringify(jsdata, null, 2);
$.ajax({
  type: "POST",
  url: "GIFacRequest.aspx/GetSubCategories",
  data: jstext ,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (dtSubCategory) {
        PopulateSubCategoryDD(dtSubCategory);
      },
      error: function (response) {
         $('body', document).html(response.responseText);
      }
  });

And my webmethod:

[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static DataTable GetSubCategories(string category)
{
}

The error i'm getting is as follows:

"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\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.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"

Pomster
  • 14,567
  • 55
  • 128
  • 204

1 Answers1

1

your variable params var jsdata = '{category:' + category + '}' is a string.

So the line: JSON.stringify(jsdata, null, 2);, is redundant (or it should be). Just set data: jsdata,

Try with this code

var jsdata = '{category:' + category + '}';
$.ajax({
  type: "POST",
  url: "GIFacRequest.aspx/GetSubCategories",
  data: jsdata ,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (dtSubCategory) {
        PopulateSubCategoryDD(dtSubCategory);
      },
      error: function (response) {
         $('body', document).html(response.responseText);
      }
  });
Sridhar R
  • 20,190
  • 6
  • 38
  • 35