0
在我的應用中,總是我想添加一個新的汽車信息到一個特定的表我必須選擇汽車的名稱,如果該汽車已經售出,我可以選擇它的所有者名稱。所以,我對於新行的表下面的代碼:訪問ViewBag數據
<td>
@Html.DropDownListFor(model => model.CarName, new SelectList(ViewBag.Cars, "Id", "Description"), new { @class = "iEdit", id = "cars"})
@Html.ValidationMessageFor(model => model.Description)
</td>
<td data-name="carOwners">
@Html.DropDownListFor(model => model.Owner, new SelectList(ViewBag.Owners, "Id", "Description"), new { @class = "iDisable", disabled = "disabled" })
@Html.ValidationMessageFor(model => model.Side)
</td>
但我怎麼能檢查,如果汽車是第一個@ Html.DropDownListFor出售所選擇的值,並啓用第二@ Html.DropDownListFor呢?
建立我ViewBag.Cars我使用此代碼我的控制器:
ICollection<Car> newListCars=new Collection<Car>();
newListCars.Add(new Car(0, "BMW", false));
newListCars.Add(new Car(1, "Toyota", true));
ViewBag.Cars= newListCars;
Car.cs:
public class Car
{
public int Id { get; set; }
public string Description { get; set; }
public bool IsSold { get; set; }
public Car(int id, string text, bool sold)
{
Id = id;
Description = text;
IsSold = sold;
}
}
所以基本上我要訪問的選擇ViewBag.Cars.IsSold
我不認爲這是一個很好的實踐,但works.Thanks – Ninita
@Ninita,你總是可以寫一個擴展方法,會更清潔。我很喜歡nikeaa在[這篇文章]中的答案(http://stackoverflow.com/questions/11285303/add-attribute-to-select-list-option#answer-11285916) – Pete