I have an application that is trying to follow Domain Driven Design to a certain extent. I have a Domain layer, and the classes inside have parameterised constructors.
My ViewModels of course have parameterless constructors, to allow for model binding. However one page is giving me problems.
One of my pages displays a List of Cars, which the user can edit the details of and then via JQuery POST the data of one car to the back end. Car is a Domain object, and has only a constructor with parameters (I do my business logic checks inside the constructor).
My code at the backend looks like this
[AjaxOnly]
public JsonResult Update(Car car)
{
//...
}
Of course this fails, because Car is a Domain class and has no parameterless constructor.
I would like to know if there is a recognised best practice for this scenario. I can think of two, possibly three options:
1) Create a parameterless constructor for the Cars domain class. Decorate it with
[Obsolete("For model binding only")]
to prevent users calling it directly. Then in my JsonResult method immediately call the parameterised constructor. Unfortunately this means changing my private setters to public in the model.
2) Accept a FormCollection, extract the values, and call the parameterised constructor. Which is similar to 1) but no change to the private setters is required.
3) Perhaps a custom model binder? I do this for my MVC controllers already for IoC but don't know how it would work for non-Controllers.
Is there a best practice way to handle this?