Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ASP.NET MVC allow private ViewModel constructor?

The question is, as in title, whether the MVC model binder allow private constructors for the view model objects. Apparently it doesn't, saying MissingMethodException: No parameterless constructor defined for this object. even if there is a private parameterless constructor. In case if there is no private constructor allowed, is there an arhitectural workaround?

Such constructor might be useful to ensure that only the model binder could create ViewModel objects whose fields might not be consistently filled - there would be no chance that in other parts of code some fields are forgotten to complete.

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

like image 619
Lorlin Avatar asked Aug 31 '12 16:08

Lorlin


1 Answers

No, it does not.

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

like image 78
SLaks Avatar answered Sep 23 '22 23:09

SLaks