MVC. Bind TextBoxFor to a Field of type object

心不动则不痛 提交于 2019-12-24 14:26:29

问题


Suppose the following code:

public class Person 
{
    public object Age { get; set;}
}

Inside view:

@Html.TextBoxFor(x => x.Age, new { @type = "number" })

Now when posting the Form, the typeOf person.Age property is string[1]. Why?

Shouldn't there be some input type based, Type pick-up logic, when binding things?


回答1:


You can't use the *For helpers with a property of type object. These helpers need to do type inference in order to create the right type of input with the right name and attributes. An object could literally be anything.

I'm not sure why you're using object for a property like Age (isn't that fairly obviously a int?). However, if you truly need to do that, I would recommend using a view model where you can define a more concrete type for the purposes of your view. Then, you can simply map the posted value back onto your object property.



来源:https://stackoverflow.com/questions/30242579/mvc-bind-textboxfor-to-a-field-of-type-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!