views:

37

answers:

2

If for example you have a Car class and that Car class contains a car type which is reflected by a table in the database. How do I get MVC to bind to car type when I create a new car?

public class Car  
{  
public string Name { get; set; }  
public CarType Type { get; set; }  
}

public class CarType   
{  
public int CarTypeId { get; set; }  
public string Name { get; set; }  
}

public class CarViewModel  
{   
 public Car MyCar { get; set; }  
 public SelectList Types { get; set; }  
}

..... inside my controller

public ActionResult Create()  
{  
 return View(new CarViewModel { Car = new Car(), Types = new SelectList(repo.GetCarTypes(), "CarTypeId", "Name") });  
}  

[HttpPost]  
public ActionResult Create(Car myCar)  
{   
 //hopefully have bound correctly  
 repo.Add(car);  
  repo.Save();  
}

What do I need in my view in order to get my Car object to be able to correctly bind?

Thank you!

+1  A: 

I think something like the following should be handled by the binder without issue.

<input name="car.name" value="" />
<select name="car.type.cartypeid">
<% foreach (var item in Model.Types) { %>
<option name="car.type.carttypeid" value="<%:item.cartypeid%>"><$:item.name%></>
<% } %>
</select>
Hal
A: 

here's what has worked for me:

<%= Html.DropDownList( "Type.CarTypeId", Model.Types ) %>

and if you're editing a Car, you'll need to set the selected value when you create your SelectList:

Types = new SelectList(repo.GetCarTypes(), "CarTypeId", "Name", car.Type.CarTypeId ) 
dave thieben