意译:http://dotnet.dzone.com/news/using-html-5-data-attributes
HTML 5的data属性是一种在DOM元素中存储数据的方式,例如我们有一个用户列表,为客户端以后使用想存储用户Id。
1 <ul>
2 <li data-id=”4” data-role=”admin”>thorsteinsson</li>
3 <li data-id=”23” data-role=”user”>john</li>
4 </ul>
public class User
{
public int Id { get; set; }
public string Role { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
这样使用:
<ul>
<% foreach (var user in Model.Users) { %>
<li <%= Html.ToDataAttributes(user) %>><%=user.Username%></li>
<% } %>
</ul>
如果我们想在html标签中不显示用户名和密码,可以跳过它:
<%= Html.ToDataAttributes(user, new { “Username”, “Password” }) %>
扩展方法的完整代码:
public static string ToDataAttributes(this HtmlHelper helper, object obj)
{
return helper.ToDataAttributes(obj, new string[] {});
}
public static string ToDataAttributes(this HtmlHelper helper, object obj, IEnumerable<string> skip)
{
StringBuilder builder = new StringBuilder();
Type t = obj.GetType();
foreach (var field in t.GetProperties())
{
if (skip.Contains(field.Name)) continue;
var value = field.GetValue(obj, null);
if (value != null)
{
builder.Append(" data-").Append(field.Name.ToLower()).Append("=\"").Append(helper.AttributeEncode(value)).Append("\"");
}
}
return builder.ToString();
}