views:

1553

answers:

2

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?

+1  A: 

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

Wayne Kao
I was looking for this everywhere! Thanks!
DrJokepu
A: 

I'm not sure what the advantage is of using a ModelBinder versus an ObjectFilter for this, but here's a solution I figured out that uses a custom ModelBinder.

http://stackoverflow.com/questions/1077481/how-do-i-pass-a-dictionary-as-a-parameter-to-an-actionresult-method-from-jquery-a

Chris Pietschmann