gpt4 book ai didi

c# - POST json 字典

转载 作者:IT老高 更新时间:2023-10-28 12:55:10 30 4
gpt4 key购买 nike

我正在尝试以下方法:带有字典的模型在第一个 ajax 请求上发送它,然后将结果再次序列化并将其发送回 Controller 。

这应该测试我可以在我的模型中取回字典。它不起作用

这是我的简单测试:

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; }
}

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) {
}
});
}
});
});

在 firebug 中接收到的 json 和发送的 json 是相同的。我只能假设有些东西在途中丢失了。

有人知道我做错了什么吗?

最佳答案

一个不幸的解决方法:

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 库函数(使用 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
});
}

正在发布的 ViewModel 对象(可能比字典还多):

public class TestViewModel
{
. . .
//public Dictionary<string, string> dictionary { get; set; }
public string dictionary { get; set; }
. . .
}

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
}

关于c# - POST json 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4710729/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com