【发布时间】:2015-05-18 19:04:02
【问题描述】:
从数据库中获取数据并添加我计划作为默认选择的选项:
public List<Forester> GetForesters()
{
var data = _db.tblForester.ToList();
List<Forester> ForesterList = new List<Forester>();
foreach (var item in data)
{
Person person = new Person()
{
Key_ = item.Key_,
FirstName = item.FirstName,
LastName = item.LastName,
District = item.District,
County = item.County
};
PersonList.Add(person);
}
PersonList.Add(new Person { Key_ = -1, FirstName = "- Select ", LastName = "Person -" } );
return PersonList;
}
模型有两个属性:
public int SelectedPersonId { get; set; }
public IEnumerable<SelectListItem> PersonList { get; set; }
控制器从数据库中获取列表并制作一个选择列表:
vm.SelectedPersonId = -1;
vm.PersonList = new SelectList(repo.GetPeople(), "Key_", "PersonsName", vm.SelectedpersonId);
我在视图中尝试了几种方法:
@Html.DropDownListFor(m => m.Key_, new SelectList( Model.PersonList, "Value", "Text", -1), new { @class = "form-control ddl" })
下拉菜单效果很好,除了所选值只是列表中的第一个,而不是我指定的那个。
以下是 HTML 的呈现方式:
<form action="/Forester/Activity" method="post"><select class="form-control ddl" data-val="true" data-val-number="The field Key_ must be a number." data-val-required="The Key_ field is required." id="Key_" name="Key_"><option value="1">DIANE PARTRIDGE</option>
<option value="2">GARY GROTH</option>
...
我添加的在底部:
<option value="-1">- Select Forester -</option>
【问题讨论】:
标签: asp.net asp.net-mvc razor html.dropdownlistfor selectlist