在我的应用中,我总是希望在特定的桌子上添加新的汽车信息我必须选择汽车名称,如果该汽车已售出,我可以选择它的所有者名称。所以我有新行表的代码:
<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
答案 0 :(得分:0)
您可以通过执行以下操作来创建自己的下拉列表,而不是使用dropdownlistfor
:
<select name="CarName" class="iEdit" id="cars">
@foreach(Car car in ViewBag.Cars)
{
<option value="@car.Id" data-issold="@(car.IsSold ? "true" : "false")">@car.Description</option>
}
</select>
然后你可以像这样使用所选选项的数据属性(jQuery):
var selected = $('#cars').find('option:selected');
var isSold = selected.data('issold');