POST json dictionary

后端 未结 10 935
猫巷女王i
猫巷女王i 2020-11-27 05:52

I\'m trying the following : A model with a dictionary inside send it on the first ajax request then take the result serialize it again and send it back to the controller.

10条回答
  •  天命终不由人
    2020-11-27 06:30

    An unfortunate workaround:

    data.dictionary = {
        'A': 'a',
        'B': 'b'
    };
    
    data.dictionary = JSON.stringify(data.dictionary);
    
    . . .
    
    postJson('/mvcDictionaryTest', data, function(r) {
        debugger;
    }, function(a,b,c) {
        debugger;
    });
    

    postJSON js lib function (uses jQuery):

    function postJson(url, data, success, error) {
        $.ajax({
            url: url,
            data: JSON.stringify(data),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: success,
            error: error
        });
    }
    

    The ViewModel object being posted (presumably has a lot more going on than a dictionary):

    public class TestViewModel
    {
        . . .
        //public Dictionary dictionary { get; set; }
        public string dictionary { get; set; }
        . . .
    }
    

    The Controller method being posted to:

    [HttpPost]
    public ActionResult Index(TestViewModel model)
    {
        var ser = new System.Web.Script.Serialization.JavascriptSerializer();
        Dictionary dictionary = ser.Deserialize>(model.dictionary);
    
        // Do something with the dictionary
    }
    

提交回复
热议问题