2

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:

  1. Have a parameterless constructor
  2. 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! :-)

Guillaume S.
  • 1,515
  • 1
  • 8
  • 21
  • Properties are used for public stuff, also they give you much more control. You can format values, do lookups etc. – Charles Jan 08 '20 at 19:19
  • 1
    Does this answer your question: https://stackoverflow.com/questions/7789674/asp-net-mvc-model-binding-excludes-class-fields – sam Jan 08 '20 at 19:19

1 Answers1

0

To answer your question

why it can't make use of public fields rather than properties?

A model binder can make use of public fields (an example of one was provided by sam in the comments). The default model binder currently doesn't - but to know why you'd have to ask them as they don't seem to have documented this design decision in the source code (as far as I can see)...

They appear to make use of PropertyDescriptors https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.propertydescriptor?view=netframework-4.8 so perhaps just didn't want to create an alternative for fields, just to support them when they pose no benefit over properties.

Another possible explanation (total guess) is that Interfaces can have properties, but not fields, and they may be using interfaces in deeper parts of the code to represent certain types of binding scenarios.

Milney
  • 6,253
  • 2
  • 19
  • 33
  • Indeed the answer pointed by @sam does explain it's a design decision from .NET team(s) ; toddmo shows customer binder which use fields is technically possible and simple. Thank for making your suggestion ; I guess now the answer of "why" would is too debatable. I will accept your answer but can you say where do you know "They appear to make use of PropertyDescriptors"? As I'm digging into .NET **Core** it can be nice to point the exact namespace/file in the repository? – Guillaume S. Jan 08 '20 at 19:40