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" } };
    type: "GET",
    data : obj

This is what it sends to the server:


or, unencoded:


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 in case of non-numeric array index. The sample code, adapted from the following StackOverflow answer is like this:

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

Which produces the following result, happily consumed by MVC:


Leave a Reply

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

You are commenting using your 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