如何发布一个空数组(int型)(jQuery的 - > MVC 3) [英] How to post an empty array (of ints) (jQuery -> MVC 3)

查看:97
本文介绍了如何发布一个空数组(int型)(jQuery的 - > MVC 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery我通过将数组中的数据参数,例如张贴 INT 的数组到我的MVC 3应用程序,以便:数据:{ myIntArray:myIntArray} 。在我的控制器,接收动作具有作为一个参数 INT [] myIntArray

Using jQuery I am posting an array of int to my MVC 3 application by putting the array in the data parameter like so: data: { myIntArray: myIntArray }. In my controller, the receiving action has as a parameter int[] myIntArray.

这顺利的话在大多数情况下,除了当 myIntArray 是空的。在请求我看到下面的 myIntArray = (需要注意的是后=无空格)。早在我的MVC 3控制器这被翻译成包含数组有一个 INT :0。

This goes well in most cases, except when myIntArray is empty. In the request I see the following myIntArray= (note that there is no space after "="). Back in my MVC 3 controller this gets translated to an array containing one int: 0.

它似乎并不像我,我张贴的空数组做一些可怕的错误在这里。我可以通过处理其中阵列是用不同的方式空的情况下解决这个问题。不过,我觉得这应该是可能的。

It doesn't seem to me like I am doing something terribly wrong here by posting an empty array. I can work around this by handling the case where the array is empty in a different way. Nevertheless, I feel that this should be possible.

先谢谢了。

额外的信息:


  • 我使用jQuery 1.5.1(无法为这个项目升级)。

  • myIntArray
    与初始化新的Array()

  • I use jQuery 1.5.1 (cannot upgrade for this project).
  • myIntArray is initialized with new Array().

推荐答案

您可以这样做:

var myIntArray = new Array();

// add elements or leave empty
myIntArray.push(1);
myIntArray.push(5);

var data = myIntArray.length > 0 ? { myIntArray: myIntArray } : null;

$.ajax({
    url: '@Url.Action("someAction")',
    type: 'POST',
    data: data,
    traditional: true,
    success: function (result) {
        console.log(result);
    }
});

或使用JSON请求:

var myIntArray = new Array();
// add elements or leave empty
myIntArray.push(1);
myIntArray.push(5);

$.ajax({
    url: '@Url.Action("someAction")',
    type: 'POST',
    data: JSON.stringify(myIntArray),
    contentType: 'application/json',
    success: function (result) {
        console.log(result);
    }
});

这篇关于如何发布一个空数组(int型)(jQuery的 - > MVC 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆