public static class ListOfT
{
public static List<SelectListItem> ToSelectList<T>(this List<T> value,
Func<T, string> getText,
Func<T, string> getValue,
string selectedValue)
{
List<SelectListItem> items = new List<SelectListItem>();
foreach (var item in value)
{
items.Add(new SelectListItem
{
Text = getText(item),
Value = getValue(item),
Selected = selectedValue == getValue(item)
});
}
return items
.OrderBy(l => l.Text)
.ToList();
}
}
样本用法:
[HttpGet]
public ActionResult Create()
{
List<State> states = new List<State>() { new State {Name = "Michigan", StateCode = "MI" },
new State {Name = "Connecticut", StateCode = "CT" }};
StateAssessmentCreateViewModel stateAssessmentViewModel = new StateAssessmentCreateViewModel();
stateAssessmentViewModel.States = states.ToSelectList(state => state.Name, state => state.StateCode, "CT");
return View(stateAssessmentViewModel);
}
查看:
@Html.DropDownListFor(model => model.StateCode, Model.States, "-- None -- ", new { htmlAttributes = new { @class = "form-control" })
我认为我在视图中的语法错误,因为formcontrol类属性格式不正确。但请注意确定原因。
<div class="form-group">
<label class="control-label col-md-2" for="StateCode">State</label>
<div class="col-md-10">
<select htmlAttributes="{ class = form-control }" id="StateCode" name="StateCode"><option value="">-- None -- </option>
<option selected="selected" value="CT">Connecticut</option>
<option value="MI">Michigan</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="CancelDate" data-valmsg-replace="true"></span>
</div>
</div>
.
答案 0 :(得分:1)
您的项目包含Select
:
public static List<SelectListItem> ToSelectList<T>(this List<T> source,
Func<T, string> getText,
Func<T, string> getValue,
string selectedValue)
{
return source
.Select(x => new SelectListItem
{
Text = getText(x),
Value = getValue(x),
Selected = selectedValue == getValue(x)
})
.ToList();
}