我正在使用 asp.net mvc。我有这个 Action :
[HttpPost]
public ActionResult Create(MyData myData)
{
.... // For some reason data is always empty. The attributes are all null
}
我的数据是:
public class MyData {
public string prop1 {get;set;}
public IEnumerable<int> prop2 {get;set;}
}
我这样调用它:
var specificData = { prop1: 'abc', prop2: [1,2,3] }
$.ajax({
type: 'POST',
dataType: 'json',
url: '/MyController/Create',
data: { myData: specificData }, //data contains the same attributes as MyData class
success: function (data, b,c,d) {
alert("success!");
},
error: function (data, b, c, d) {
alert('fail');
}
});
问题在于,在 Create 操作中,“data”变量被实例化,但它的属性均为空。我做错了什么吗?
更新
根据 @Rory McCrossan 的说法,我通过使用 data: SpecificData
而不是 data: { myData: SpecificData }
来解决这个问题。但现在我在另一个地方遇到了这个问题。序列化问题与 MyData 类相关,因为现在我使用更复杂的类:
公共(public)类人{
公共(public)字符串名称{get;set;}
}
public class MyData {
public string prop1 {get;set;}
public IEnumerable<Person> prop2 {get;set;}
}
具体数据是:
var specificData = { prop1: 'abc',
prop2: [
{name:'a'},
{name:'b'},
{name:'c'}]
};
在操作中,myData.prop2.ElementAt(0).name 为 null。 现在出了什么问题?
最佳答案
创建要发送的 JS 对象时,您将属性包装在 myData
属性中,但这不是必需的。试试这个:
$.ajax({
data: specificData
// other settins...
});
关于javascript - ajax 调用 mvc 操作中的空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13375557/