问题
Obviously, ASP.NET MVC's binding functionality takes care of binding a model's public properties when passing it to a controller, so for instance in the following example, Surname
and Email
will be bound with their submitted values:
public ActionResult Create(UserModel mdlNewUser) {
// ...
}
// ...
public class UserModel {
public string Firstname;
public string Surname { get; set; }
public string Email { get; set; }
}
However, it doesn't seem to auto-bind public fields such as Firstname
in the above example; these will be left untouched. Is there any way to get public fields (and for that matter, any other type of class member) to be automatically bound, or will it only ever bind public properties?
This article seems to imply that it's only public properties because it only ever refers to them all the way through, but it doesn't explicitly seem to say that only public properties will be bound.
回答1:
That's correct, only public properties will be bound.
Fields cannot be used for binding.
来源:https://stackoverflow.com/questions/16240611/binding-public-fields-with-asp-net-mvc-as-well-as-public-properties