Take the 2-minute tour ×

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; }



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


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 ?


share|improve this question
You're probably only posting back the category id. You'd need to know on the server side how to get the correct Category instance from your persistence layer. –  Ryan Apr 28 '10 at 16:37

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
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 Apr 29 '10 at 0:08

Your Answer


