Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC automatically decoding JSON-encoded parameters from AJAX

When my JavaScript code uses AJAX to call an ASP.NET MVC method, it passes values in JSON. For example:

var request = new XMLHttpRequest();
request.open("GET", "http://www.awesome.com/DoSomething?param1=%22some%20string%22&param2=1234", true);  // parameter string created with JSON.stringify

or

var request = new XMLHttpRequest();
request.open("POST", "http://www.awesome.com/DoSomething", true);
// set some headers
request.send("param1=%22some%20string%22&param2=1234");  // parameter string created with JSON.stringify

On the ASP.NET MVC side, I have my method to handle the call:

public void DoSomething(string param1, string param2) {

What sucks is param1 is surrounded with quotation marks:

"some string"

What sucks more is param2 is the string:

1234

when I really want the value as an integer. So, the first thing I have to do is use DataContractJsonSerializer to decode both these puppies so my string doesn't have quotation marks and my second string is converted to an int. It's not too bad the first one or two times, but gets old having to do for every single AJAX action.

Ideally, it'd be awesome to have a signature like:

public void DoSomething(string param1, int param2)

where I could just jump right in and use my values without worrying about JSON decoding, just like is done for non-AJAX actions.

Is there a way to do this?

like image 499
Wayne Kao Avatar asked Nov 06 '22 22:11

Wayne Kao


1 Answers

Oh, after posting I found code that does what I'm looking for. See the "ObjectFilter" class near the bottom:

http://weblogs.asp.net/omarzabir/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx

like image 181
Wayne Kao Avatar answered Nov 11 '22 03:11

Wayne Kao