I'm developing a web application with ASP.NET Core with MVC. The controllers' actions that handle POST requests from a HTML form
usually accept a parameter used as a binding model like:
[HttpPost]
public IActionResult Edit(ModelBindingClass userInput)
I discovered that the class for a binding model, in the example above ModelBindingClass
, must respect two conditions:
- Have a parameterless constructor
- Have publicly settable properties to store user inputs
I suppose the first condition is to ensure the MVC middleware can easily instantiate an object.
But why it can't make use of public fields rather than properties?
public class ModelBindingClass
{
public int Age { get; set; } // binder will set it correctly
public int Height; // binder will not
}
Any answer pointing to the related source code is welcomed. Thank! :-)