3

Is there a way to pass this javascript object

Object { 35=true, 179=true, 181=true}

into a controller action as

Dictionary<int, bool>

I've checked the following methods:

    var remoteUrl = "@Url.Action("UpdateProjectStructureSelection")" + "?tlpId=@Model.TopLevelProjectId";
    $.post(remoteUrl, mapSiteSelectionChoices, function(callbackResult) {
        alert(callbackResult);
    });

and

    var remoteUrl = "@Url.Action("UpdateProjectStructureSelection")" + "?tlpId=@Model.TopLevelProjectId";
    $.post(remoteUrl, { values : mapSiteSelectionChoices }, function(callbackResult) {
        alert(callbackResult);
    });

However in both cases

public ActionResult UpdateProjectStructureSelection(int tlpId, Dictionary<int, bool> values)

has been called, but values was empty.

Since i've transfered more complex types into a controller action without writing a custom model binder i've been wondering whether i'm just doing something wrong here.

Is a custom model binder the only way here to get it as dictionary? (other than using JsonConvert + stringify on clientside)

Addition (This works but i'd love to avoid extra code) :

    public ActionResult UpdateProjectStructureSelection(int tlpId, string values)
    {
        var dict = JsonConvert.DeserializeObject<Dictionary<int, bool>>(values);
    }
Dbl
  • 5,634
  • 3
  • 41
  • 66

1 Answers1

3

Not with the object in that format. It would need to be in the following format to be used by the DefaultModelBinder

var data = { 'dict[0].key': '35', 'dict[0].value': 'True', 'dict[1].key': '179', 'values[1].value': 'True', dict[0].key': '8', 'dict[0].value': 'True' };
$.post(remoteUrl, data, function(callbackResult) {

and the controller

public ActionResult UpdateProjectStructureSelection(Dictionary<int, bool> dict)

As you noted, another option is to use a custom ModelBinder, for example this answer

Community
  • 1
  • 1
  • such a shame. but it does make sense that it doesn't work with that object notation. Thank you. – Dbl Feb 03 '15 at 12:06