Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize a JavaScript object as Dictionary<string, string> via ModelBinding in Web API

I have a simple JavaScript string and object:

var name = "Scarlett Johansson";
var args = { arg1: "foo", arg2: "bar" };

And I want to pass them via $.ajax to a Web API controller:

public string Get([FromUri]TestClass input) {
    // would like Args model-bound 
}

And my TestClass is:

public class TestClass
{
    public string Name { get; set; }
    public Dictionary<string, string> Args { get; set; }
}

The Name property is bound as expected, but I haven't found a way to bind Args. I've tried JSON.stringify(args), $.param(args), using a List<KeyValuePair<string,string>> on TestClass instead of Dictionary, nothing has worked.

I was hoping I could achieve this via model binding instead of manually de-serializing the JSON. Is this possible?

Clarification: the number of keys/values would vary in "args" from call to call, hence my need for a Dictionary.

like image 694
Darren Mart Avatar asked Mar 15 '26 23:03

Darren Mart


1 Answers

the default model binding wont work like that, it attempts to bind to public properties on objects. in this example, you would need a class containing like :

public class ArgClass
{
    public string Arg1 { get; set; }
    public string Arg2 { get; set; }
}

public class TestClass
{
    public string Name { get; set; }
    public List<ArgClass> Args { get; set; }
}

the alternative, which seems like you would want to do, is write a custom model binder, or a quick google search turns up this DefaultDictionaryBinder someone seems to have implemented already

https://github.com/loune/MVCStuff/blob/master/Extensions/DefaultDictionaryBinder.cs

Update: just realized you are using web api, which is i guess slightly different. Here's a blog post explaining how the binding works for web api: http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

like image 89
Kevin Nacios Avatar answered Mar 18 '26 13:03

Kevin Nacios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!