List转MVC DropDownListFor(SelectList)

时间:2023-12-20 17:37:08
 /// <summary>
/// List转SelectListItem
/// </summary>
/// <typeparam name="T">Model对象</typeparam>
/// <param name="t">集合</param>
/// <param name="text">显示值-属性名</param>
/// <param name="value">显示值-属性名</param>
/// <param name="empId"></param>
/// <returns></returns>
public static List<SelectListItem> CreateSelect<T>(IList<T> t, string text, string value,string empId)
{
List<SelectListItem> l = new List<SelectListItem>();
foreach (var item in t)
{
var propers = item.GetType().GetProperty(text);
var valpropers = item.GetType().GetProperty(value);
l.Add(new SelectListItem
{
Text = propers.GetValue(item, null).ToString(), Value = valpropers.GetValue(item, null).ToString(),
Selected = valpropers.GetValue(item, null).ToString() == empId
});
}
return l;
}

调用:

List<HrEmp> list = LoadData();
List<SelectListItem> emplist = CreateSelect<HrEmp>(list, "EmpName", "EmpId",entity.HrEmpGuid.ToString());
ViewData["Emp"] = new SelectList(emplist, "Value", "Text");

视图调用:

  @Html.DropDownListFor(t => t.HrEmpGuid, ViewData["Emp"] as SelectList, new { @class = "form-control select2" })