Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using HTML 5 data attributes with ASP.NET MVC

DZone's Guide to

Using HTML 5 data attributes with ASP.NET MVC

· Web Dev Zone
Free Resource

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

HTML 5 data attributes are a way to store data on a DOM element. Check out the spec for more information. For example we have a list of users and want to store the id of the user on the client side for later use. Here is a sample markup.

<ul>
    <li data-id=”4” data-role=”admin”>thorsteinsson</li>
    <li data-id=”23” data-role=”user”>john</li>
</ul>

On the server side we have a class for the user.

public class User
{
    public int Id { get; set; }
    public string Role { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

To make it more simple to make these data attributes, I made a extension method for HtmlHelper.

<ul>
    <% foreach (var user in Model.Users) { %>
    <li <%= Html.ToDataAttributes(user) %>><%=user.Username%></li>
    <% } %>
</ul>

If we don’t want to write the username and password to the markup we can choose to skip it.

<%= Html.ToDataAttributes(user, new { “Username”, “Password” }) %>

Here is the complete code for this extension method.

    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();
    }

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Ægir Þorsteinsson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}