Tag: development

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

Explicit vs Implicit

Choosing implicit over explicit in programming is hard, because both ways have their pros and cons.

Explicit implementation is easy to understand and debug, but usually amounts to a lot of boilerplate code and is hard to maintain. It’s tempting us to shout DRY and invent some clever “automagic” to ease the burden.

But implicit implementation can quickly become plagued by a lot of special cases and ad-hoc add ons and so is prone to lose all its initial elegance and conciseness. In addition, implicit code is often hard to debug and difficult to get into for new developers.

So what to choose? I usually try to follow a simple empirical rule: favor implicit in infrastructure and explicit in your business logic. And check whether you really have the pros promised: if implicit implementation is hard to set up (as with many XML-configured libraries) or explicit implementation is obscure and buggy, it’s a good idea to re-evaluate your decisions.