ASP.NET MVC/C#: Can I create valid custom HTML attributes using Html.ActionLink()?

那年仲夏 提交于 2019-12-08 16:05:06

问题


I have the need to put a custom attribute on an anchor which I am constructing using Html.ActionLink()

<%: Html.ActionLink("Delete", "Delete", new { id = Model.ID }, new { data-icon = "ui-icon-trash" })%>

Using the proper "data-" prefix, as per http://www.w3.org/TR/html5/elements.html#attr-data, I get the following error from Visual Studio.

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

Since I can't use a hyphen in the anonymous type, what would be the best way to go about adding my custom HTML attribute?


回答1:


data-icon is not a valid C# variable name. The closest you could get is this:

<%: Html.ActionLink(
    "Delete", 
    "Delete", 
    new { id = Model.ID }, 
    new Dictionary<string, string> { { "data-icon",  "ui-icon-trash" } }
) %>

Of course this issue has been addressed in ASP.NET MVC 3 and you no longer need to write spaghetti code. So:

<%: Html.ActionLink(
    "Delete", 
    "Delete", 
    new { id = Model.ID }, 
    new { data_icon, "ui-icon-trash" }
) %>

And the underscore will be automatically converted to a hyphen.



来源:https://stackoverflow.com/questions/4235434/asp-net-mvc-c-can-i-create-valid-custom-html-attributes-using-html-actionlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!