Asp.net-Mvc
如何在 ASP.NET MVC 中的 HTML-5 data-* 屬性中使用破折號
我正在嘗試在我的 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" })%>上述 htmlAttributes 中的“數據詳細資訊”給出以下錯誤:
CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.它在我使用 data_details 時有效,但我想它需要按照規範以“data-”開頭。
我的問題:
- 有沒有辦法讓這個工作和使用 HTML5 數據屬性與 Html.ActionLink 或類似的 Html 助手?
- 是否有任何其他替代機制可以將自定義數據附加到元素?這些數據稍後將由 JS 處理。
更新:MVC 3 和更新版本對此具有內置支持。有關推薦的解決方案,請參閱下面的 JohnnyO 高度贊成的答案。
我認為沒有任何直接的幫手可以實現這一目標,但我確實有兩個想法供您嘗試:
// 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" ) )%>只是想法,沒有測試過。
此問題已在 ASP.Net MVC 3 中得到解決。它們現在自動將 html 屬性屬性中的下劃線轉換為破折號。他們很幸運,因為下劃線在 html 屬性中是不合法的,因此 MVC 可以自信地暗示您在使用下劃線時想要破折號。
例如:
@Html.TextBoxFor(vm => vm.City, new { data_bind = "foo" })將在 MVC 3 中呈現:
<input data-bind="foo" id="City" name="City" type="text" value="" />如果您仍在使用舊版本的 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; } }然後你可以像這樣使用它:
<%: Html.TextBoxFor(vm => vm.City, Foo.AnonymousObjectToHtmlAttributes(new { data_bind = "foo" })) %>這將呈現正確的 data-* 屬性:
<input data-bind="foo" id="City" name="City" type="text" value="" />