Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
May 13, 2010 04:31 AM|LINK
why is it that I need a parameterless constructor for ASP.NET MVC to instantiate an object on the fly when saving a form?
It is not needed in saving the form, but needed when Model Binding
Let you explain,
When you define a simple class without constructor, then compiler will automatcally add a parameterless construstor during compilation. So this class
public class A
is equal to this class
public class A
if you define a constructor in your class explicitly, then compiler will not add extra constructor.
So if you add a constructor with parameter then Model binding will have no idea what values provide in this constructor parameter. That's why Model Binding looks for paremeterless constructor.
As Steve said in his book,
When DefaultModelBinder needs to instantiate custom object types (e.g., Person in the previous example), it uses .NET’s Activator.CreateInstance() method, which relies on those types having public parameterless constructors. If your types don’t have parameterless
constructors, or if you want to instantiate them using an IoC container, then you can derive a subclass of DefaultModelBinder, override its virtual method CreateModel(), and then assign an instance of your custom binder to ModelBinders.Binders.DefaultBinder.
Alternatively, you can implement a custom binder just for that specific type. An example of a custom binder follows shortly.