使 List 对象与 ASP.NET MVC3 中前端的发布数据兼容
我有以下控制器,我通过 AJAX 以表单形式发布到:
[HttpPost]
public ActionResult Create(List<int> listOfSTuff)
{
try
{
service.Create(listOfSTuff);
}
catch
{
return null;
}
return Json(new { gid = 7 }); // hardcoded for simplicity
}
我很难让 jQuery AJAX 帖子使 List
数据类型与帖子数据兼容。这是我的 jQuery/JavaScript 代码:
var listOfStuff = [1, 2, 3];
$.ajax({
type: 'POST',
url: '/MyController/Create',
data: listOfStuff,
success: function(data) {
alert(data.gid);
},
error: alert(':('),
dataType: 'json'
});
我知道控制器的 AJAX 发布正在工作,因为我得到了 gid
但我没有看到数组元素 1
或 2
或 3
保存在数据库中。控制器似乎并不喜欢我正在传递的 JavaScript 数组。谁能建议前端的数据结构应该是什么样子,以使其与控制器操作期望的 List
兼容?
I have the following controller that I am posting to in a form via AJAX:
[HttpPost]
public ActionResult Create(List<int> listOfSTuff)
{
try
{
service.Create(listOfSTuff);
}
catch
{
return null;
}
return Json(new { gid = 7 }); // hardcoded for simplicity
}
I am having a hard time with my jQuery AJAX post making the List
data type compatible with the post data. Here is my jQuery/JavaScript code:
var listOfStuff = [1, 2, 3];
$.ajax({
type: 'POST',
url: '/MyController/Create',
data: listOfStuff,
success: function(data) {
alert(data.gid);
},
error: alert(':('),
dataType: 'json'
});
I know that the AJAX post to the controller is working because I get a gid
but I do not see the array elements 1
or 2
or 3
saved in the database. It does not appear that the controller likes my JavaScript array that is being passed over. Can anyone suggest how the data structure should look like from the frontend to make it compatible with the List
that the controller action is expecting?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让你的 listOfStuff 声明如下:
在将发布的数据发布到控制器之前,将其格式化为正确的 JSON 对象会更好。所以现在:
data: listOfStuff
,将发布一个正确的 JSON 字符串并将控制器中的参数名称更改为:
希望它适合您。
Make your listOfStuff declared as such:
It works better to format your posted data as a proper JSON object before posting it to the controller. so now:
data: listOfStuff
, will post a proper JSON stringand change the parameter name in your Controller to be:
Hope it works for you.
事实证明,我在 jQuery AJAX 调用中缺少一个关键参数,该参数使此工作正常进行:
有一个
traditional
属性,默认情况下为false
,但必须设置它为true
,它使用 param 序列化 的传统风格。It turns out that I was missing a critical parameter in the jQuery AJAX call that makes this work:
There is a
traditional
attribute that isfalse
by default but it has to be set totrue
which uses the traditional style of param serialization.