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
{
public 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,
Steve
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.
"And whoever is removed away from the Fire and admitted to Paradise, he indeed is successful." (The Holy Quran)
Excellent Windows VPS Hosting Imran Baloch MVP, MVB, MCP, MCTS, MCPD
imran_ku07
All-Star
45815 Points
7698 Posts
MVP
Re: No parameterless constructor defined for this object
May 13, 2010 04:31 AM|LINK
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
{
public 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,
Excellent Windows VPS Hosting
Imran Baloch MVP, MVB, MCP, MCTS, MCPD