ASP.NET MVC DropdownList的使用

1:直接使用HTML代码写

<select name="year">
    <option value="2011">2010</option>
    <option value="2012">2011</option>
    <option value="2013">2012</option>
    <option value="2014">2013</option>
</select>

效果:

ASP.NET MVC  DropdownList的使用

2:将枚举中的值写入到 DropdownList

假设有个枚举:

 1 namespace MvcDropdownList.Controllers
 2 {
 3     public class EnumController : Controller
 4     {
 5         // GET: /Enum/
 6         private const string ZHOUYI = "语文";
 7         private const string ZHOUER = "数学";
 8         private const string ZHOUSAN = "物理";
 9         private const string ZHOUSI = "化学";
10         private const string ZHOUWU = "英语";
11         private const string ZHOULIU = "C语言";
12         private const string ZHOUQI = "ASP.NE";
13 
14         public enum Days
15         {
16             Monday =1,
17             Tuesday = 2,
18             Wednesday = 3,
19             Thursday = 4,
20             Friday = 5,
21             Saturday = 6,
22             Sunday = 7
23         }
24 
25         public static IDictionary<int, string> BindData()
26         {
27             IDictionary<int, string> dict = new Dictionary<int, string>();
28 
29             dict.Add((int)Days.Monday, ZHOUYI);
30             dict.Add((int)Days.Tuesday, ZHOUER);
31             dict.Add((int)Days.Wednesday, ZHOUSAN);
32             dict.Add((int)Days.Thursday, ZHOUSI);
33             dict.Add((int)Days.Friday, ZHOUWU);
34             dict.Add((int)Days.Saturday, ZHOULIU);
35             dict.Add((int)Days.Sunday, ZHOUQI);
36 
37             return dict;
38         }
39         public ActionResult Index2()
40         {
41             return View();
42         }
43     }
44 }

拓展类:

 1 namespace MvcDropdownList.Models
 2 {
 3     public static class TestExtention
 4     {
 5         public static MvcHtmlString DropDownList(this HtmlHelper helper, string name, IDictionary<int,string> dict, string key, string value)
 6         {
 7             SelectList selectListItems = new SelectList(dict, key, value);
 8             return helper.DropDownList(name, selectListItems);
 9         }
10     }
11 }

前台:

1 <body>
2     <div>
3         @Html.DropDownList("saaa", MvcDropdownList.Controllers.EnumController.BindData(),"Key","Value")      
4     </div>
5 </body>

注意前台页面需要添加前面两个类的引用:

1 @using MvcDropdownList.Models
2 @using MvcDropdownList.Controllers;

效果:

ASP.NET MVC  DropdownList的使用