问题
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