2010-07-30 155 views
0

例如,如果您有Car类,并且Car类包含汽车类型,该类型由数据库中的表反映。我如何在创建新车时将MVC绑定到车型?Asp.net MVC Binding

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

我需要什么,我认为,为了得到我的车对象能够正确绑定?

谢谢!

回答

1

这里是为我工作:

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

,如果你正在编辑一个车,你会当你创建的SelectList需要设置所选值:

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

我认为像下面这样的东西应该由活页夹处理没有问题。

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