我使用as
填充下拉列表[Required(ErrorMessage = "Please make a selection")]
public string SelectedPrimary { get; set; }
public IEnumerable<SelectListItem> PrimaryDrop { get; set; }
public void populateDropdown()
{
primaryDrop = new List<string>();
primaryDrop.Insert(0, "Getting ready");
primaryDrop.Insert(1, "Starting");
primaryDrop.Insert(2, "All");
PrimaryDrop = primaryDrop.Select(item => new SelectListItem { Value = item, Text = item });
}
然后我的剃刀观点如下
@Html.DropDownListFor(m => m.SelectedPrimary, new SelectList(Model.PrimaryDrop, "Value", "Text"), "Learning Path", new { style = "width:207px;", id = "FirstDropDown" })
在检查元素时,我会看到这个
<select data-val="true" data-val-required="Please make a selection" id="FirstDropDown" name="SelectedPrimary" style="width:207px;">
<option value="">Learning Path</option>
<option value="Getting ready">Getting ready</option>
<option value="Starting">Starting</option>
<option value="All modules">All</option>
</select>
我怎样才能将值设置为索引?
<select data-val="true" data-val-required="Please make a selection" id="FirstDropDown" name="SelectedPrimary" style="width:207px;">
<option value="0">Learning Path</option>
<option value="1">Getting ready</option>
<option value="2">Starting</option>
<option value="3">All modules</option>
</select>
答案 0 :(得分:1)
您可以这样填写PrimaryDrop
(使用List<T>.IndexOf(T)
获取Value
)
primaryDrop = new List<string>();
primaryDrop.Insert(0, "Getting ready");
primaryDrop.Insert(1, "Starting");
primaryDrop.Insert(2, "All");
PrimaryDrop = primaryDrop.Select(item => new SelectListItem
{
Value = primaryDrop.IndexOf(item),
Text = item
});
答案 1 :(得分:1)
您可以使用Dictionary来构建SelectList。然后使用key作为值和值作为文本
var primaryDrop = new Dictionary<string, string>() {
{"0", "Getting Ready"},
{"1", "Starting"},
{"2", "All"}
};
PrimaryDrop = primaryDrop.Select(item =>
new SelectListItem { Value = item.Key, Text = item.Value });