Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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")" + "[email protected]";
    $.post(remoteUrl, mapSiteSelectionChoices, function(callbackResult) {
        alert(callbackResult);
    });

and

    var remoteUrl = "@Url.Action("UpdateProjectStructureSelection")" + "[email protected]";
    $.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);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
539 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...