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

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

asp.net mvc - Transmit javascript object into controller action as dictionary

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...