Dav*_*ave 121 c# asp.net-mvc jquery
我正在尝试将通过AJAX的int(或IEnumerable)数组传递给MVC操作,我需要一些帮助.
javascript是
$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...
Run Code Online (Sandbox Code Playgroud)
并且控制器动作是
public ActionResult MyAction(IEnumerable<int> arrayOfValues )
Run Code Online (Sandbox Code Playgroud)
目前请求的格式为
controller/MyAction?_=1301503418429&arrayOfValues[]=491&arrayOfValues[]=368&arrayOfValues[]=235&arrayOfValues[]=437
Run Code Online (Sandbox Code Playgroud)
所以我几乎就在那里,如果我取下方括号,我会得到正确的答案.我应该如何将该数组传递给我的get,以便控制器可以识别它是什么?
非常感谢您的帮助
戴夫
Cha*_*ndu 148
在进行get调用之前将traditional属性设置为true.即:
jQuery.ajaxSettings.traditional = true
$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...
Run Code Online (Sandbox Code Playgroud)
Rio*_*ams 116
我在尝试执行POST时遇到过问题(不确定这是否正是你正在做的事情,但我记得在传入数组时,必须将传统设置为true.
var arrayOfValues = new Array();
//Populate arrayOfValues
$.ajax({
type: "POST",
url: "<%= Url.Action("MyAction","Controller")%>",
traditional: true,
data: { 'arrayOfValues': arrayOfValues }
});
Run Code Online (Sandbox Code Playgroud)
SNa*_*Nag 49
这里已有的答案相当晚,但答案不同:
如果$.ajax您不想使用速记函数,$.get或者$.post您可以通过这种方式传递数组:
速记GET
var array = [1, 2, 3, 4, 5];
$.get('/controller/MyAction', $.param({ data: array }, true), function(data) {});
Run Code Online (Sandbox Code Playgroud)
// Action Method
public void MyAction(List<int> data)
{
// do stuff here
}
Run Code Online (Sandbox Code Playgroud)
速记POST
var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});
Run Code Online (Sandbox Code Playgroud)
// Action Method
[HttpPost]
public void MyAction(List<int> data)
{
// do stuff here
}
Run Code Online (Sandbox Code Playgroud)
笔记:
$.param用于
traditional属性,必须true使其工作.使用"传统"选项的答案是正确的.我只是为希望了解更多内容的人提供更多背景信息.
从jQuery文档:
从jQuery 1.8开始,$ .param()方法不再使用jQuery.ajaxSettings.traditional作为其默认设置,默认为false.
您还可以在这里阅读更多内容:http: //michaelsync.net/2012/04/05/tips-asp-net-mvc-javascriptserializer-3-questions-and-3-answers 和 http://haacked.com/archive /2008/10/23/model-binding-to-a-list.aspx
HTH
你应该能够做到这一点:
$.ajax({
url: 'controller/myaction',
data: JSON.stringify({
myKey: myArray
}),
success: function(data) { /* Whatever */ }
});
Run Code Online (Sandbox Code Playgroud)
然后你的行动方法是这样的:
public ActionResult(List<int> myKey)
{
// Do Stuff
}
Run Code Online (Sandbox Code Playgroud)
对你来说,看起来你只需要对你的值进行字符串化.MVC中的JSONValueProvider会将它转换回IEnumerable.
| 归档时间: |
|
| 查看次数: |
148005 次 |
| 最近记录: |