<li>
<label for="Client_StateProvince">StateProvince:</label>
<div>
<%= Html.DropDownListFor(c=>c.Client.StateProvince, new SelectList(Model.StateProvinces, "id", "Name", Model.Client.StateProvince), "-- Select State --")%>
</div>
<%= Html.ValidationMessage("Client.StateProvince")%>
</li>
这似乎不够好。我错过了什么?
答案 0 :(得分:78)
<%= Html.DropDownListFor(c => c.Client.StateProvince.Id,
new SelectList(Model.StateProvinces,
"id",
"Name",
Model.Client.StateProvince),
"-- Select State --")%>
就是这样。
希望这有助于其他人。
〜利
答案 1 :(得分:7)
对我来说非常合适!我用它在子类别上设置父关系:
<%= Html.DropDownListFor(
model => model.Category.ParentId,
new SelectList(Model.Categories,
"CategoryId",
"Name",
Model.Categories.Where(x => x.CategoryId == Model.Category.ParentId).Single()))%>
的Jeroen
答案 2 :(得分:4)
控制器
IFarmModelInterface service2 = new FarmModelRepository();
ViewData["Farms"] = new SelectList(service2.GetFarmNames(), "id", "FarmName", "XenApp");
查看
<%: Html.DropDownListFor(m => m.Farm, (ViewData["Farms"] as SelectList)) %>
答案 3 :(得分:3)
public ActionResult AllUsers()
{
List<Users> users = userRep.GetUsers();
var listUsers = (from u in users.AsEnumerable()
select new SelectListItem
{
Text = u.UserName,
Value = u.UserId.ToString(),
Selected = (u.UserId==6)
}).AsEnumerable();
ViewBag.ListItems = listUsers;
//ViewBag.SelectedItem = 2;
return View();
}
在AllUsers.cshtml中
<p>@Html.DropDownList("ListItems")</p>
答案 4 :(得分:2)
<%= Html.DropDownListFor(c => c.Client.StateProvince, new SelectList(Model.StateProvinces, "Id", "Name")) %>
并覆盖StateProvince的ToString()以返回Id,即:
return Id.ToString();
这可行,但不是一个完美的解决方案......
丹尼斯
答案 5 :(得分:1)
这是视图 - MVC控制器
@Html.DropDownListFor(m => m.Entity, new ABC.Models.DropDownPopulate().MyMethod, new { @class = "form-control input-inline input-medium" })
MyMethod 使用SelectListItems获取数据列表与下拉列表绑定
public List<SelectListItem> MyMethod
{
get
{
List<SelectListItem> dropdownList = new List<SelectListItem>();
var items = new DropDown_Bl().GetAll();
foreach (var item in items)
{
SelectListItem dropdownItem = new SelectListItem();
dropdownItem.Value = item.RnID.ToString();
dropdownItem.Text = item.Description;
dropdownList.Add(dropdownItem);
}
dropdownList.Insert(0, new SelectListItem() { Text = "Please Select", Value = "", Selected = true });
return dropdownList;
}
}
Dropdown_Bl中的GetAll方法 - 用于从数据库中获取数据列表
public List<My_Table> GetAll()
{
var Items = _Context.MyRepository.GetMany(q => q.Area == "ASD").ToList();
return Items ;
}
答案 6 :(得分:0)
public ActionResult AllUsers() {
List<Users> users = userRep.GetUsers();
var listUsers = (from u in users.AsEnumerable()
select new SelectListItem
{
Text = u.UserName,
Value = u.UserId.ToString(),
Selected = (u.UserId==6)
}).AsEnumerable();
// ViewBag.ListItems = listUsers;
ViewData["tempEmpList"]=listUsers;
return View(); }
填写下拉列表
@Html.DropDownList("SelectedEmployee", new SelectList((IEnumerable) ViewData["tempEmpList"], "Id", "Name"))