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! :-)

2
  • Properties are used for public stuff, also they give you much more control. You can format values, do lookups etc. Commented Jan 8, 2020 at 19:19
  • 1
    Does this answer your question: stackoverflow.com/questions/7789674/… Commented Jan 8, 2020 at 19:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.