Enum简单例子DropdownList

借鉴:http://www.cnblogs.com/suizhikuo/archive/2013/06/07/3125225.html

vs2012 mvc4

最终效果:

1、建立mvc4 Internet应用程序

2、Models下建立Product.cs类

 public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int TypeId { get; set; }

    }

    public enum TypeName
    {
        糖果类,
        干果类,
        水果类
    }

    public class EnumExt 
    { 
        public static List<ListItem> ToListItem<T>() 
        { 
            List<ListItem> li = new List<ListItem>(); 
            foreach (int s in Enum.GetValues(typeof(T))) 
            { 
                li.Add(new ListItem { Value = s.ToString(), Text = Enum.GetName(typeof(T), s) }); 
            } 
            return li; 
        } 
    }

  3、在AccountModels.cs下 数据库上下文UsersContext类中添加实体集集合

          

            public DbSet<Product> Products { get; set; }

4、重新生成解决方案

5、添加控制器ProductController

6、ProductController.cs下 Create方法 ,添加

 public ActionResult Create()
        {
            ViewBag.TypeId = new SelectList(EnumExt.ToListItem<TypeName>(), "Value", "Text");
            return View();
        }

 Edit方法 ,添加

 public ActionResult Edit(int id = 0)
        {
            Product product = db.Products.Find(id);
            ViewBag.TypeId = new SelectList(EnumExt.ToListItem<TypeName>(), "Value", "Text",product.TypeId);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

7、视图页面Create修改

@Html.EditorFor(model => model.TypeId) 修改为

  @Html.DropDownList("TypeId")

视图页面Edit修改

@Html.EditorFor(model => model.TypeId) 修改为

  @Html.DropDownList("TypeId")

视图页面Index 修改

 @Html.DisplayFor(modelItem => item.TypeId)修改为

 @Enum.GetName(typeof(MvcApplication2.Models.TypeName),item.TypeId)

8、运行 添加数据 查看

源代码:http://pan.baidu.com/s/1i3xBIF7

后来发现:

foreach (int s in Enum.GetValues(typeof(T))) 此处若 int s写为 var s ,得到的序列值和文本全是文字了,不知原因 注意
原文地址:https://www.cnblogs.com/heifengwll/p/3476851.html