如何在 ASP.NET MVC 中的 HTML-5 data-* 属性中使用破折号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2520487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use dashes in HTML-5 data-* attributes in ASP.NET MVC
提问by Shameem
I am trying to use HTML5 data- attributesin my ASP.NET MVC 1 project. (I am a C# and ASP.NET MVC newbie.)
我正在尝试在我的 ASP.NET MVC 1 项目中使用HTML5 数据属性。(我是 C# 和 ASP.NET MVC 新手。)
<%= Html.ActionLink("? Previous", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new { @class = "prev", data-details = "Some Details" })%>
The "data-details" in the above htmlAttributes give the following error:
上面 htmlAttributes 中的“data-details”给出了以下错误:
CS0746: Invalid anonymous type member declarator. Anonymous type members
must be declared with a member assignment, simple name or member access.
It works when I use data_details, but I guess it need to be starting with "data-" as per the spec.
当我使用 data_details 时它有效,但我想它需要按照规范以“data-”开头。
My questions:
我的问题:
- Is there any way to get this working and use HTML5 data attributes with Html.ActionLink or similar Html helpers ?
- Is there any other alternative mechanism to attach custom data to an element? This data is to be processed later by JS.
- 有什么方法可以让这个工作并使用 HTML5 数据属性与 Html.ActionLink 或类似的 Html 助手?
- 是否有其他替代机制可以将自定义数据附加到元素?这个数据后面会被JS处理。
采纳答案by Morten Mertner
Update: MVC 3 and newer versions have built-in support for this. See JohnnyO's highly upvoted answer below for recommended solutions.
更新:MVC 3 和更新版本对此有内置支持。有关推荐的解决方案,请参阅下面 JohnnyO 高度赞成的答案。
I do not think there are any immediate helpers for achieving this, but I do have two ideas for you to try:
我不认为有任何直接的帮助可以实现这一目标,但我确实有两个想法供您尝试:
// 1: pass dictionary instead of anonymous object
<%= Html.ActionLink( "back", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new Dictionary<string,Object> { {"class","prev"}, {"data-details","yada"} } )%>
// 2: pass custom type decorated with descriptor attributes
public class CustomArgs
{
public CustomArgs( string className, string dataDetails ) { ... }
[DisplayName("class")]
public string Class { get; set; }
[DisplayName("data-details")]
public string DataDetails { get; set; }
}
<%= Html.ActionLink( "back", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new CustomArgs( "prev", "yada" ) )%>
Just ideas, haven't tested it.
只是想法,还没有测试过。
回答by Johnny Oshika
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.
这个问题已经在 ASP.Net MVC 3 中得到解决。他们现在自动将 html 属性中的下划线转换为破折号。他们在这一点上很幸运,因为下划线在 html 属性中是不合法的,所以 MVC 可以自信地暗示您在使用下划线时需要破折号。
For example:
例如:
@Html.TextBoxFor(vm => vm.City, new { data_bind = "foo" })
will render this in MVC 3:
将在 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:
如果您仍在使用旧版本的 MVC,您可以通过创建我从 MVC3 的源代码中借用的静态方法来模拟 MVC 3 正在做什么:
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:
这将呈现正确的 data-* 属性:
<input data-bind="foo" id="City" name="City" type="text" value="" />
回答by Oliver
It's even easier than everything suggested above. Data attributes in MVC which include dashes (-) are catered for with the use of underscore (_).
它甚至比上面建议的所有内容都容易。MVC 中包含破折号 (-) 的数据属性使用下划线 (_) 来满足。
<%= Html.ActionLink("? Previous", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new { @class = "prev", data_details = "Some Details" })%>
I see JohnnyO already mentioned this.
我看到 JohnnyO 已经提到了这一点。
回答by mzonerz
In mvc 4 Could be rendered with Underscore(" _ ")
在 mvc 4 中可以用 Underscore(" _ ") 渲染
Razor:
剃刀:
@Html.ActionLink("Vote", "#", new { id = item.FileId, }, new { @class = "votes", data_fid = item.FileId, data_jid = item.JudgeID, })
Rendered Html
渲染的 Html
<a class="votes" data-fid="18587" data-jid="9" href="/Home/%23/18587">Vote</a>
回答by WestDiscGolf
You can implement this with a new Html helper extension function which will then be used similarly to the existing ActionLinks.
您可以使用新的 Html 帮助程序扩展函数来实现此功能,然后该函数将与现有的 ActionLinks 类似地使用。
public static MvcHtmlString ActionLinkHtml5Data(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes, object htmlDataAttributes)
{
if (string.IsNullOrEmpty(linkText))
{
throw new ArgumentException(string.Empty, "linkText");
}
var html = new RouteValueDictionary(htmlAttributes);
var data = new RouteValueDictionary(htmlDataAttributes);
foreach (var attributes in data)
{
html.Add(string.Format("data-{0}", attributes.Key), attributes.Value);
}
return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null, actionName, controllerName, new RouteValueDictionary(routeValues), html));
}
And you call it like so ...
你这样称呼它......
<%: Html.ActionLinkHtml5Data("link display", "Action", "Controller", new { id = Model.Id }, new { @class="link" }, new { extra = "some extra info" }) %>
Simples :-)
简单:-)
edit
编辑
bit more of a write up here
多写一点在这里
回答by Keith Williams
I ended up using a normal hyperlink along with Url.Action
, as in:
我最终使用了一个普通的超链接和Url.Action
,如下所示:
<a href='<%= Url.Action("Show", new { controller = "Browse", id = node.Id }) %>'
data-nodeId='<%= node.Id %>'>
<%: node.Name %>
</a>
It's uglier, but you've got a little more control over the a
tag, which is sometimes useful in heavily AJAXified sites.
它更丑陋,但您对a
标签有更多的控制权,这有时在大量 AJAX 化的站点中很有用。
HTH
HTH
回答by msa.im
I do not like use pure "a" tag, too much typing. So I come with solution. In view it look
我不喜欢使用纯“a”标签,打字太多。所以我提出了解决方案。鉴于它看起来
<%: Html.ActionLink(node.Name, "Show", "Browse",
Dic.Route("id", node.Id), Dic.New("data-nodeId", node.Id)) %>
Implementation of Dic class
Dic类的实现
public static class Dic
{
public static Dictionary<string, object> New(params object[] attrs)
{
var res = new Dictionary<string, object>();
for (var i = 0; i < attrs.Length; i = i + 2)
res.Add(attrs[i].ToString(), attrs[i + 1]);
return res;
}
public static RouteValueDictionary Route(params object[] attrs)
{
return new RouteValueDictionary(Dic.New(attrs));
}
}
回答by gururaj nadager
You can use it like this:
你可以这样使用它:
In Mvc:
在 Mvc 中:
@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});
In Html:
在 HTML 中:
<input type="text" name="Id" data_val_number="10"/>