sir*_*cco 22 c# post json dictionary asp.net-mvc-3
我正在尝试以下内容:带有字典的模型将其发送到第一个ajax请求,然后将结果再次序列化并将其发送回控制器.
这应该测试我可以在模型中找回字典.它不起作用
这是我的简单测试:
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; }
}
Run Code Online (Sandbox Code Playgroud)
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) {
}
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
在萤火虫中,json接收并且发送的json是相同的.我只能假设在途中迷路了.
任何人都知道我做错了什么?
Chr*_*ini 22
一个不幸的解决方法:
data.dictionary = {
'A': 'a',
'B': 'b'
};
data.dictionary = JSON.stringify(data.dictionary);
. . .
postJson('/mvcDictionaryTest', data, function(r) {
debugger;
}, function(a,b,c) {
debugger;
});
Run Code Online (Sandbox Code Playgroud)
postJSON js lib函数(使用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
});
}
Run Code Online (Sandbox Code Playgroud)
正在发布的ViewModel对象(可能比字典还要多得多):
public class TestViewModel
{
. . .
//public Dictionary<string, string> dictionary { get; set; }
public string dictionary { get; set; }
. . .
}
Run Code Online (Sandbox Code Playgroud)
Controller方法发布到:
[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
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 14
由于JsonValueProviderFactory的实现方式,不支持绑定字典.
直接使用 ASP.NET 5 和 MVC 6 我正在这样做:
JSON:
{
"Name": "somename",
"D": {
"a": "b",
"b": "c",
"c": "d"
}
}
Run Code Online (Sandbox Code Playgroud)
控制器:
[HttpPost]
public void Post([FromBody]Dictionary<string, object> dictionary)
{
}
Run Code Online (Sandbox Code Playgroud)
这是通过时显示的内容(名称和 D 是键):