JS int数组到MVC3控制器
我在JS中有一个字符串数组。 所有成员实际上都是数字。
我的控制器有一个int []参数。
我从jquery发送它:
$.ajax({url: someUrl, data: {ids : JSON.stringify(id_array) }, ...)
我用它来收到它
public ActionResult MyAction(int[] ids) { ...
参数没有被填充,我已经检查过, Request.Form["ids"]
包含“ [\"25\",\"26\"]"
,JSON数组的字符串表示。 有没有办法在没有大量int解析的情况下自动执行此操作?
您是否尝试过不对数组进行字符串化并让mvc的默认模型绑定发挥作用
$.ajax({url: someUrl, data: {ids : id_array }, ...)
我很确定.net MVC会看到数组并看到它是一个int数组并正确地将它映射到你的int数组
对于MVC3,您需要配置jQuery以使用传统的“浅层”序列化。请参见此处 。
客户端AJAX请求:
jQuery.ajaxSettings.traditional = true; //enable "shallow" serialisation globally $.get("someUrl", {ids : id_array });
行动方法:
public ActionResult MyAction(string[] ids) { ... }
您可以通过两种不同的方式完成此操作
1.使用$ .ajax将数据发布到您的操作中
$.ajax({ url: '/myController/myAction', dataType: 'json', type: 'POST', contentType: 'application/json; charset=utf-8', traditional: true, data: $.toJSON(json), success: function (data, textStatus, jqXHR) { ... } });
你的行动应该像这样
public class myController { [HttpPost] public ActionResult myAction(List json) { .... } }
2.使用$ .post发布您的数据
$.post( '/myController/myAction', { json: $.toJSON(products) }, function (data) { ... });
在您的操作中,您应该反序列化JSON字符串
public class myController { public ActionResult myAction(string json) { JavaScriptSerializer serializer = new JavaScriptSerializer(); List list = serializer.Deserialize>(json); } }
您需要下载并将jquery.json-2.2.min.js包含在您的代码中。
http://code.google.com/p/jquery-json/downloads/detail?name=jquery.json-2.2.min.js
你需要使用
$.ajax({ url: someUrl, data: id_array.map( function(item){ return {name:'ids',value:item}; }) })
这是因为为了在后端接收列表,需要以ids=3&ids=5&ids=1&ids=7
的forms发送数据
对于不支持.map
使用的IE版本
function arrayToParamObject(name,array){ var obj = []; for (var i = 0, len = array.length; i< len; i++){ obj.push( {name: name, value: array[i] } ); } return obj; }
并使用它
$.ajax({ url: someUrl, data: arrayToParamObject('ids', id_array) })