gpt4 book ai didi

c# - javascript : json object with arrays serialized for use in . NET MVC 操作

转载 作者:行者123 更新时间:2023-12-01 08:00:23 24 4
gpt4 key购买 nike

简单问题:

我想将一些数据发布到这样的操作:

        var data = {
Prop1 : 'a',
ListOfObjects: [{ PropertyA: 1, PropertyB: 2 }, { PropertyA: 3, PropertyB: 4}]
};

当我通过 JQuery AJAX 将此数据发送到我的 Action 时,我的模型已部分填充:

public class MyObject{
public int PropertyA {get;set;}
public int PropertyB {get;set;}
}

public class MyModel{
public string Prop1 {get;set;}
public List<MyObject> ListOfObjects {get;set;}
}

public JsonResult Save(MyModel model)
.
.
.
model.Prop1 //Is okay!
model.ListOfObjects[0] // is okay too...List has 2 items
model.ListOfObjects[0].PropertyA; //Nope...no values inside this model...

我猜原因是,序列化的HTTP数据是错误的,它们就像ListOfObjects[0][PropertyA] <- 但应该是 ListOfObjkects[0].PropertyA

有人知道该怎么办吗?

编辑:我的 JQuery AJAX 代码:

$.ajax({
type: 'POST',
url: saveURL,
dataType: 'json',
data: data,
complete: function () {
DeleteMainLoader();
},
success: function success(data, textStatus, jqXHR) {
if (data.success) {
alert('win!')
}
else {
alert('error');
}

},
error: function (jqXHR, textStatus, errorThrown) {
alert('errrrrooooorrrr');
}
});

最佳答案

如果您使用 ASP.NET MVC 3 或更高版本,最简单的方法是发送 JSON 而不是 URL 编码数据。这使得复杂的嵌套对象更容易使用,因为 jQuery 此时不需要理解任何 ASP.NET MVC 的约定。

为此,只需构建一个与服务器端类匹配的对象,将其字符串化,并确保在请求上设置 application/json 内容类型:

var data = {
Prop1 : 'a',
ListOfObjects: [{ PropertyA: 1, PropertyB: 2 }, { PropertyA: 3, PropertyB: 4}]
};

$.ajax({
type: 'POST',
url: saveURL,
// This is unnecessary; jQuery will detect the response's dataType based
// on its Content-Type header automatically.
dataType: 'json',
// This sets the request's Content-Type to let MVC know how to interpret the
// data parameter.
contentType: 'application/json',
// I can't remember if this is 100% necessary in this case, but some ASP.NET
// endpoints only work if you match up the method's parameter name like this.
data: JSON.stringify({ model: data })
});

关于c# - javascript : json object with arrays serialized for use in . NET MVC 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20195886/

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