码迷,mamicode.com
首页 > Web开发 > 详细

List转MVC DropDownListFor(SelectList)

时间:2017-08-13 23:22:34      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:pid   return   复制   opd   tab   ext   table   down   logs   

/// <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");

视图调用:

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

List转MVC DropDownListFor(SelectList)

标签:pid   return   复制   opd   tab   ext   table   down   logs   

原文地址:http://www.cnblogs.com/sjqq/p/7355099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!