【问题标题】:ASP.NET MVC Int Array parameter with empty array defaults to {0}带有空数组的 ASP.NET MVC Int Array 参数默认为 {0}
【发布时间】:2011-05-01 11:34:46
【问题描述】:

我有一个控制器动作,例如:

Public ActionResult MyAction(int[] stuff){}

我发出如下 JSON 请求:

$.getJSON(url, { stuff: [] })

当它到达 C# 时,它看起来像一个包含一个元素的数组,它是零(即就像我做了 int[] stuff = {0}; 一样)。

这是 MVC 2 或 .NET 4 的新功能吗?最近好像变了,但我还没有找到确凿的证据。我怎样才能解决这个问题?这不可能是预期的行为,不是吗?

【问题讨论】:

  • 您还会注意到此行为与 AJAX/JSON 无关。如果您调用控制器并通过查询字符串传递“stuff”(例如 /MyAction?stuff= ),您将得到相同的结果
  • 这里接受的答案很好地分解:stackoverflow.com/questions/23108272/…

标签: asp.net asp.net-mvc asp.net-mvc-2


【解决方案1】:

我认为这是 MVC 中的一个错误:

// create a vpr with raw value and attempted value of empty string
ValueProviderResult r = new ValueProviderResult("", "", System.Globalization.CultureInfo.CurrentCulture);
// this next line returns {0}
r.ConvertTo(typeof(int[]));

如果我们查看函数 UnwrapPossibleArrayType 中的 ValueProviderResult.cs,我们会看到:

// case 2: destination type is array but source is single element, so wrap element in array + convert
object element = ConvertSimpleType(culture, value, destinationElementType);
IList converted = Array.CreateInstance(destinationElementType, 1);
converted[0] = element;
return converted;

它强制 converted[0] 成为元素,并且 ConvertSimpleType 将“”强制转换为 0。所以我要结束这个问题,除非有人有更多信息。

编辑:另外,这不在修订版 17270 中,所以如果您要列出从 MVC 1 更改为 MVC 2 的内容,这就是其中之一。

【讨论】:

    【解决方案2】:

    当我测试代码时,我在控制器操作中得到了 null 数组,而不是一个包含一个元素的数组。

    在 jquery 1.4 及更高版本中,在 AJAX 请求期间序列化参数的方式已更改,并且不再与默认模型绑定器兼容。执行请求时可以设置traditional参数:

    $.getJSON(url, $.param({ stuff: [ 1, 2, 3 ] }, true));
    

    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'JSON',
        data: { stuff: [ 1, 2, 3 ] },
        traditional: true,
        success: function(res) { }
    });
    

    【讨论】:

    • 我使用的是传统的,但我仍然得到这个。见赫克托的评论;当您输入 url ?var= 时,问题仍然存在
    猜你喜欢
    • 2012-09-12
    • 2010-10-19
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2013-01-22
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多