Does ASP.NET MVC provide a private ViewModel constructor?

The question is, as in the title, does the MVC middleware allow private constructors for view model objects. Apparently, this is not so MissingMethodException: No parameterless constructor defined for this object., even if there is a private constructor without parameters. If the use of a private constructor is allowed, is there a workaround for the architecture?

Such a constructor can be useful to ensure that only object-objects-objects can create ViewModel objects whose fields cannot be sequentially filled - there would be no chance that in other parts of the code some fields will be forgotten to complete.

Entity Framework can use private constructors and private properties in a similar situation.

+6
source share
2 answers

No, it is not.

If you want the actual code to not call this constructor, you can add [Obsolete("For model binding only", true)]to the public constructor. This will cause a compiler error if the constructor is explicitly called.

+14
source

You can always write a custom mediator that supports private / secure ctors.

+1
source

All Articles