为什么asp.net mvc模型绑定器生成system.string []

Ben*_*ter 5 asp.net-mvc-3

我有一个表单,它将有效的对象字典发布到我的控制器操作中.所以我们得到一个IEnumerable<EditThemeAttributeModel>

        public class EditThemeAttributeModel
        {
            public string Name { get; set; }
            public object Value { get; set; }
        }
Run Code Online (Sandbox Code Playgroud)

当我查看Request.Form集合时,我看到了我的期望:

    [1] "Attributes[0].Name"    string
    [2] "Attributes[0].Value"   string
    [3] "Attributes[1].Name"    string
    [4] "Attributes[1].Value"   string
    [5] "Attributes[2].Name"    string
    [6] "Attributes[2].Value"   string
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试获取其中一个的值时,EditThemeAttributeModel它并不像我期望的那样简单,它是一个字符串数组:

-   Value   {string[1]} object {string[]}
                [0] "#ffffff"   string
Run Code Online (Sandbox Code Playgroud)

我可以通过直接使用Request.Forms集合来解决这个问题,但只是想了解这种行为.

Bui*_*ted 4

默认情况下,来自 http 请求的所有帖子都是字符串。由于您引用的是对象而不是类型对象,因此它默认为字符串,因为来自浏览器的数据是字符串。如果您希望它不是字符串,我建议您键入您的对象,或者您可以为EditThemeAttributeModel.

  • 因为默认情况下,您可以为给定的帖子值包含相同名称的多个值。`id=1&amp;id=2&amp;id=3` 因为您不是专门要求一个 `string` 而是一个 `object`,所以模型绑定程序假定它可以是一个数组,因为它无法将其直接转换为类型。数组创建是模型绑定器的最后一次调用,因为它基本上无法弄清楚您真正想要什么。我猜它这样做只是为了安全。 (2认同)