accessing the parameters of a JSON call in the web method-Collection of common programming errors
I have the following JSON call, the data I’m passing seems to be getting stringify’ed properly from what i’m looking at, however, I don’t seem to have the right syntax to process the parameter in the public web method.
Here is the JSON call:
var qs = new Querystring();
var v1 = qs.get("TorVName");
var jsonData = JSON.stringify(v1);
$().ready(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetColumns",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var optString = 'Select Column';
$.each(msg.d, function(index, item) {
optString += '' + item + '';
});
$('select[name^=DDLColumns]').html(optString);
},
error: function() {
alert("Failed to load columns");
}
});
});
and here is the cooresponding web method:
[WebMethod]
public static ArrayList GetColumns(string TorVName)
{
String cnstr = "myconnect string";
string Sql = String.Empty;
ArrayList arlist = new ArrayList();
SqlDataReader rdr = null;
SqlCommand cmd = null;
DataSet dset;
SqlConnection cn = new SqlConnection(cnstr);
cn.Open();
dset = new DataSet("ds");
dset.Clear();
etc etc…
I have a hard time deciding how to debug a web method since I can only see the client side actions in firebug.
any help on how to recieve and process the parameter in the web method would be most appreciated.
Thanks Deano
-
Your data needs to be in name/value pair format, like this:
var jsonData = JSON.stringify({ TorVName: qs.get("TorVName") });
The web method is looking for the property named
TorVName
, so you need a name/value pair with this for your JSON request, not just the string. In the above code theTorVName:
is because that’s what the parameter is named in the web method. -
as others have stated, you need ot have a json object with a parameter of torVName since htat is what your web method is looking for. an easy way to do this is var data={};//create new object data[‘torVName’]=actual datta’; then in your ajax call you can just say data:JSON.stringify(data)
-
maybe you guys should read this before suggesting the stringify stuff in IE8:
JSON returns ‘undefined’ when stringifying an object that was created in a different window See test case at http://kinsey.no/examples/ie8_json_bug/
Originally posted 2013-11-10 00:11:47.