pass dictionary to controller asp.net mvc

前端 未结 3 1634
臣服心动
臣服心动 2020-12-15 05:39

I am wanting to pass a dictionary of type to my controller via an Ajax post. The main reason here is the post may have between 1-3 key value pai

相关标签:
3条回答
  • 2020-12-15 05:43

    JavaScript object / dictionary has to be passed as a list of key-value pairs to ASP.NET MVC controller when Dictionary<TKey, TValue> is expected. Example:

    If you have a dictionary like this:

    public Dictionary<string, decimal?> SomeMapping { get; set; }
    

    then you have to use something like this in your JavaScript:

    var sourceMapping = { a: 1, b: 1.5, c: null };
    var SomeMapping = [];
    for (var key in sourceMapping) {
        if (sourceMapping.hasOwnProperty(key)) {
            SomeMapping.push({ Key: key, Value: sourceMapping[key] });
        }
    }
    

    I've used this approach in asynchronous POST request (sent using jQuery) that had content type set to 'application/json' (this may or may not be important in your case).

    0 讨论(0)
  • 2020-12-15 05:53

    Client (JavaScript):

    var dict = new Object();
    dict.Key1 = "Value1"
    dict.Key2 = "Value2"
    
    $.post('/YourController/YourAction/', dict);
    

    NOTE: The "dict" objects gets serialized behind the scenes before being sent to your action.

    Server:

    public ActionResult YourAction()
    {
        string postData = string.Empty;
        using (StreamReader sr = new StreamReader(Request.InputStream))
        {
            postData = sr.ReadToEnd();
        }    
    
        //Load post data into JObject (Newtonsoft.Json)
        JObject o = JObject.Parse(postData);
    
        //Extract each key/val 
        string val1 = (string)o["Key1"];
    
        //Do whatever....
    }
    
    0 讨论(0)
  • 2020-12-15 05:55

    Something like (javascript)

    dict = new Object();
    dict['12'] = 5;
    dict['13'] = 6;
    dict['1000'] = 21;
    dict['9'] = 13;
    dict['13'] = 48;
    
    $.post('/client.mvc/mypostaction/', { myDictionary: dict });
    

    You can then post the dict object to your controller using a Dictionary<int, int> as property type.

    ActionResult MyPostAction(Dictionary<string, int> myDictionary)
    

    edit from author's code second time:

    The following works for me, when having a Dictionary<string, int> kvPairs. <int, int> isn't going to work after all.

    Make your post like:

    var dict = new Object();
    dict['13'] = 9;
    dict['14'] = 10;
    dict['2'] = 5;
    
    $.post('controller.mvc/Test', { 'kvPairs': dict }, function(obj) { $('#output').html(obj.Count); }); 
    
    0 讨论(0)
提交回复
热议问题