标签:
@Html.DropDownList("sex", new SelectList(Enum.GetValues(typeof(enumSex))), new { @class = "form-control",data_bind="value: Sex"})
1、mvc htmlhelper 中加入data-属性,应改为data_
This problem has been addressed in ASP.Net MVC 3. They now automatically convert underscores in html attribute properties to dashes. They got lucky on this one, as underscores are not legal in html attributes, so MVC can confidently imply that you‘d like a dash when you use an underscore.
For example:
@Html.TextBoxFor(vm => vm.City, new { data_bind = "foo" })
will render this in MVC 3:
<input data-bind="foo" id="City" name="City" type="text" value="" />
If you‘re still using an older version of MVC, you can mimic what MVC 3 is doing by creating this static method that I borrowed from MVC3‘s source code:
public class Foo { public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes) { RouteValueDictionary result = new RouteValueDictionary(); if (htmlAttributes != null) { foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(htmlAttributes)) { result.Add(property.Name.Replace(‘_‘, ‘-‘), property.GetValue(htmlAttributes)); } } return result; } }And then you can use it like this:
<%: Html.TextBoxFor(vm => vm.City, Foo.AnonymousObjectToHtmlAttributes(new { data_bind = "foo" })) %>
and this will render the correct data-* attribute:
<input data-bind="foo" id="City" name="City" type="text" value="" />
2、枚举绑定
@Html.DropDownList("sex", new SelectList(Enum.GetValues(typeof(enumSex))), new { @class = "form-control",data_bind="value: Sex"})
@Html.DropDownListFor(model => model.DepartmentType, new SelectList(Enum.GetValues(typeof(enumDepartmentType))))
但是上两种方法只有text,没有value,所以有个优化方案如下
假设我们有一个enum:
public enum Role{ User = 0, Admin = 1024 }
因为enum本身并没有IEnumerable接口,所以不能直接使用new SelectList(Role);来将之填充DropDownList。
但是我们可以写一个静态方法将之转为IEnumerable。
public class EnumExt{ static public 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; } }
View文件中我们加入以下helper:
<%=Html.DropDownList("enumlist") %>
然后我们在Controller的action中写如下绑定即可
public ActionResult Index() { ViewData["enumlist"] = new SelectList(EnumExt.ToListItem<Role>(),"value","text"); return View(); }
这样我们就可以实现将Enum绑定在DropDownList了
前提还要有一个ListItem类
public class ListItem { public string Value { get; set; } public string Text { get; set; } }
标签:
原文地址:http://www.cnblogs.com/longyi/p/5677329.html