views:

39

answers:

4

Hi everybody

I'm begginer in asp.net mvc and i have some doubts.

P.S: I'm using DDD to learn

I have an ACtion in a Controller and it'll save an entity (from my model) by a repository (for a database). My doubts is, How can I get the informations from the View and save it by a repository in my Controller ? Is it correct to get an entity of my Model in Save method of controller, like this:

public ActionResult Save(Product product) { // validate object
// save data in repository
return View("Success"); }

Or Need I get an DTO (with a structure similar to my entity) and create an object passing property by property to an entity ? I didnt' like of FormCollection and I'd like to know, What is recommended architecturally ?

Thanks a lot guys

Cheers

A: 

As long as your form has fields which match the fields in Product, they should automatically be populated for you based on the values. How you save the entity depends on the data model, whether you're creating a new record or editing an existing one, etc.

briercan
+1  A: 

Typically, in ASP.NET MVC your controller actions will receive strongly typed objects returned by the DefaultModelBinder when editing entity types. Using this pattern you can pass a "Product" to your GET view either by itself or as part of a DTO and then your "Save" method would receive a "Product" object in its parameter list.

So long as you are using either editor templates or fields with matching names (i.e. Html.TextBox("Name") corresponds to Product.Name) then the DefaultModelBinder should be able to correctly fill the typed entity object passed to the action method. You shouldn't have to mess with the FormCollection except in certain edge cases.

[HttpGet]
public ActionResult Create() {
    return View("Create", new Product());
}

[HttpPost]
public ActionResult Create(Product product) { //or Save(Product)
    ...
}
Nathan Taylor
+1  A: 

This kind of problem can be fixed by adding so called view model.

Basically - a view model is DTO that provides data for particular view. In similar fashion - view models are used to get data back from view via model binding. Then - controller just forwards necessary data to domain model.

Arnis L.
+1  A: 

I you want to follow DDD practices as described by the Blue Book you should bind your views to DTO's which can be forwarded to a thin 'Application' layer where Domain objects are created or retrieved from database. This application layer can be a simple facade with methods or can leverage command pattern.

For a live demo, you can see my project -- DDDSample.NET

Szymon Pobiega