簡體   English   中英

Asp.net MVC綁定

[英]Asp.net MVC Binding

例如,如果您有一個Car類,並且該Car類包含一個由數據庫中的表反映的汽車類型。 創建新汽車時,如何使MVC綁定到汽車類型?

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

我需要什么才能使Car對象能夠正確綁定?

謝謝!

我認為以下內容應由活頁夾處理,而不會出現問題。

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

這對我有用:

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

如果您正在編輯汽車,則在創建SelectList時需要設置選定的值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM