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.
Due to the way JsonValueProviderFactory is implemented binding dictionaries is not supported.
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
}
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):
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();
}