如何添加数据属性在ASP.NET MVC中的HTML元素? [英] How to add data attributes to html element in ASP.NET MVC?

查看:525
本文介绍了如何添加数据属性在ASP.NET MVC中的HTML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学会<一个href=\"http://stackoverflow.com/questions/1305734/is-it-ok-to-add-your-own-attributes-to-html-elements\">few分钟前中,添加数据属性是一个很好的方式来添加自定义信息HTML元素。于是,我就这样做:

I learned few minutes ago that adding data attributes is a nice way to add custom information to html elements. So I tried to do like this:

<%= Html.TextBox ("textBox", "Value", new { data-myid = m.ID })%>

但它作为一个语法错误结束。我怎么可以定义自定义数据属性?

But it ends up as a syntax error. How can I define custom data attributes?

编辑:

我知道我可以使用达到这样的效果:

I see that I can achieve this effect using:

<%= Html.TextBox ("textBox", "Value", new Dictionary<string, object> {{ "data-myid", m.ID }})%>

但是,这不看......嗯......干净!有没有更好的方式来做到这一点?

But that doesn't look...umm...clean! Is there any better way to do this?

推荐答案

使用的下划线,而不是短跑。

新{data_myid = m.ID}

明确工作在MVC3 (没有检查其他版本)。下划线将被转换为当HTML呈现一个破折号。

This definitely works in MVC3 (haven't checked other versions). The underscore will be converted to a dash when the HTML is rendered.

这篇关于如何添加数据属性在ASP.NET MVC中的HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆