Passing complex objects to ASP.NET MVC action using HTTP GET method via jQuery ajax

Sometimes, you might encounter a minor issue in ASP.NET MVC: via AJAX, you can easily pass whatever object you want to your POST action, but doing so with GET endpoint is not so obvious. Plain object would work, but once it starts to be more complex, containing nested objects, everything breaks down and nested objects properties are never filled in.

As an example, consider this jQuery bit:

var obj= { prop1: "val1", nested: { prop2: "val2" } };
$.ajax({
    type: "GET",
    data : obj
})

This is what it sends to the server:

prop1=val1&nested%5Bprop2%5D=val2

or, unencoded:

prop1=val1&nested[prop2]=val2

It seems like array syntax is not welcomed by MVC. What IS welcomed then? Turns out, dot member access is parsed quite nicely – all we need to do is to replace foo[bar] with foo.bar in case of non-numeric array index. The sample code, adapted from the following StackOverflow answer http://stackoverflow.com/a/17580574/76176 is like this:

var obj = { prop1: "val1", nested: { prop2: "val2" } };
var data = $.param(obj).replace(/%5b([^0-9].*?)%5d/gi, '.$1');
$.ajax({
    type: "GET",
    data : data
})

Which produces the following result, happily consumed by MVC:

prop1=val1&nested.prop2=val2
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s