[英]In ASP.NET MVC, why is the parameter bound as an array when binding to an object instead of a specific type
I have a bunch of controllers with a similar delete action, so I'm putting that into a base class. 我有一堆具有类似删除操作的控制器,因此将其放入基类中。 This is what it looked like before: 这是以前的样子:
public async Task<ActionResult> Delete(int id)
{
await apiClient.Delete(id);
return new EmptyResult();
}
And in the view there's a raw link pointing to: 并且在视图中有一个原始链接指向:
/Items/Delete?Id=" + item.Id
And that works fine, but then some of the models use a string as a key in place of int. 效果很好,但随后某些模型将字符串用作int的键。 Since the API client is backed by an Entity Framework repo which can delete by object
, I just tried this: 由于API客户端由可以通过object
删除的Entity Framework存储库支持,所以我尝试了以下方法:
public async Task<ActionResult> Delete(object id)
{
await apiClient.Delete(id);
return new EmptyResult();
}
Now I am getting a single-element array bound to id
. 现在我得到一个绑定到id
的单元素数组。 The single element is the string representing the item.Id
. 单个元素是表示item.Id
的字符串。 Why's that? 为什么? Why it's an array and not simply the element? 为什么是数组而不是简单的元素?
My guess is that's actually the default format for data passed to it, since all form values are passed to the server as string, and when there are name collisions, the values are accessible as an array under that name. 我的猜测是这实际上是传递给它的数据的默认格式,因为所有表单值都以字符串形式传递给服务器,并且当发生名称冲突时,这些值可以作为该名称下的数组进行访问。 So really, string[] is the default type of all submitted values, and anything else involves some kind of automatic conversion. 因此,实际上,string []是所有提交值的默认类型,其他任何东西都涉及某种自动转换。
For example, if you had a form with three text inputs that all had the same name "text", the browser would send all three, and MVC would start out with a string array called "text". 例如,如果您有一个包含三个文本输入的表单,且所有文本输入都具有相同的名称“文本”,则浏览器将发送所有三个文本输入,而MVC将从一个名为“文本”的字符串数组开始。 Since the controller parameter type is 'object', it really can't make any smart guesses about what to do with it, so it just gives you the original array. 由于控制器参数类型为“对象”,因此它实际上无法做出任何明智的猜测,因此只能为您提供原始数组。
On the other hand, if the field type is known to be string, then it combines them into a comma separated list; 另一方面,如果已知字段类型为字符串,则将它们组合成一个逗号分隔的列表; and you could probably avoid such an unwanted concatenation step by setting the type to 'string[]'. 并且您可以通过将类型设置为'string []'来避免这种不必要的连接步骤。 If the parameter type is 'int', it tries to convert the string value to an integer. 如果参数类型为'int',它将尝试将字符串值转换为整数。 If the parameter type is 'bool', it will try to interpret the string as a Boolean. 如果参数类型为'bool',它将尝试将字符串解释为布尔值。 So, the string array is actually the normal value, and it's everything else that's receiving special transforms. 因此,字符串数组实际上是正常值,并且它是接受特殊转换的所有其他内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.