views:

48

answers:

1

Hi all, i'd like to know how can I get a property like an entity, for example:

My Model:

public class Product {

   public int Id { get; set; }
   public string Name { get; set; }
   public Category Category { get; set; }

}

View:

Name: <%=Html.TextBoxFor(x => x.Name) %>
Category: <%= Html.DropDownList("Category", IEnumerable<SelectListItem>)ViewData["Categories"]) %>

Controller:

public ActionResult Save(Product product)
{
   /// produtct.Category ???
}

and how is the category property ? It's fill by the view ? ASP.Net MVC know how to fill this object by ID ?

Thanks!

+2  A: 

This is one of the reasons why it's bad to bind directly to entities. Consider

public class ProductForm {
   public int Id { get; set; }
   public string Name { get; set; }
   public string CategoryId { get; set; }
}

public ActionResult Save(ProductForm form)
{
   var product = new Product
   {
        Id = form.Id,
        Name = form.Name,
        Category = database.GetCategory(form.CategoryId)
   };
}

In case of view models as above, it may be OK to use custom model binders to automatically get entities by Id from database. See here for sample implementation (in S#arp Architecture) that binds IDs to entities from database. But I think for now you better go with simpler implementation like above.

You can also use AutoMapper to simplify form->entity mapping.

queen3
I'd also put the list of categories into the view model, rather than in ViewData.In the Get action for the form, populate the viewmodel including all categories
Mac