POST json dictionary

后端 未结 10 738
猫巷女王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条回答
  • Due to the way JsonValueProviderFactory is implemented binding dictionaries is not supported.

    0 讨论(0)
  • 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<string, string> 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<string, string> dictionary = ser.Deserialize<Dictionary<string, string>>(model.dictionary);
    
        // Do something with the dictionary
    }
    
    0 讨论(0)
  • 2020-11-27 06:41

    Using ASP.NET 5 and MVC 6 straight out of the box I'm doing this:

    jSON:

    {
        "Name": "somename",
        "D": {
            "a": "b",
            "b": "c",
            "c": "d"
        }
    }
    

    Controller:

    [HttpPost]
    public void Post([FromBody]Dictionary<string, object> dictionary)
    {
    }
    

    This is what shows up when it comes through (Name and D are the keys):

    0 讨论(0)
  • 2020-11-27 06:41

    Post the complex object as a string and deserialize at the other end. There is no type-safety however for this. Here is a dictionary with string key and string array values.

    js:

    var data = { 'dictionary': JSON.stringify({'A': ['a', 'b'] }) };
    
    $.ajax({
        url: '/Controller/MyAction',
        data: JSON.stringify(data),
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json'
    });
    

    c# controller:

    [HttpPost]
    public ActionResult MyAction(string dictionary)
    {
        var s = new System.Web.Script.Serialization.JavaScriptSerializer();
        Dictionary<string, string[]> d = s.Deserialize<Dictionary<string, string[]>>(dictionary);
        return View();
    }
    
    0 讨论(0)
提交回复
热议问题