Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST json dictionary

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.

This should test that I can get back a dictionary in my model. It doesn't work

Here's my simple test:

public class HomeController : Controller
{
    public ActionResult Index (T a)
    {
      return View();
    }

    public JsonResult A(T t)
    {
      if (t.Name.IsEmpty())
      {
        t = new T();
        t.Name = "myname";
        t.D = new Dictionary<string, string>();
        t.D.Add("a", "a");
        t.D.Add("b", "b");
        t.D.Add("c", "c");
      }
      return Json(t);
    }
}

//model
public class T
{
  public string Name { get; set; }
  public IDictionary<string,string> D { get; set; }
}

The javascript:

$(function () {
    var o = {
        Name: 'somename',
        "D": {
            "a": "b",
            "b": "c",
            "c": "d"
        }
    };

    $.ajax({
        url: actionUrl('/home/a'),
        contentType: 'application/json',
        type: 'POST',
        success: function (result) {
            $.ajax({
                url: actionUrl('/home/a'),
                data: JSON.stringify(result),
                contentType: 'application/json',
                type: 'POST',
                success: function (result) {
                }
            });
        }
    });
});

In firebug the json received and the json sent are identical. I can only assume something gets lost on the way.

Anyone has an idea as to what I'm doing wrong?

like image 270
sirrocco Avatar asked Jan 17 '11 06:01

sirrocco


People also ask

How to POST JSON data from Python?

To post a JSON to the server using Python Requests Library, call the requests. post() method and pass the target URL as the first parameter and the JSON data with the json= parameter. The json= parameter takes a dictionary and automatically converts it to a JSON string.

How do you represent a dictionary in JSON?

Introducing JSON JSON is a way of representing Arrays and Dictionaries of values ( String , Int , Float , Double ) as a text file. In a JSON file, Arrays are denoted by [ ] and dictionaries are denoted by { } .

Can you send JSON in post?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.


3 Answers

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
}
like image 51
Chris Moschini Avatar answered Oct 18 '22 15:10

Chris Moschini


Due to the way JsonValueProviderFactory is implemented binding dictionaries is not supported.

like image 34
Darin Dimitrov Avatar answered Oct 18 '22 13:10

Darin Dimitrov


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):

enter image description here

like image 41
DrCJones Avatar answered Oct 18 '22 14:10

DrCJones