HTML5 allows the use of custom attributes prefixed with the phrase "data-" which pass validation without the use of a custom DTD (more info). In Asp.Net MVC, is there any way to specify an ActionLink with a data- attribute?
The typical method for adding attributes to an ActionLink is to pass in an anonymous object, with a custom property for each object:
new { customattribute="value" }
What I'd like to do is:
new { data-customattribute="value" }
But this doesn't work, because the hyphen character isn't valid in property names. Is there any way around this restriction? Or do I just have to choose between using ActionLinks and using data- attributes?
Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.
The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.
Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.
If you need to pass through the reference to an object that is stored on the server, then try setting a parameter of the link to give a reference to the object stored on the server, that can then be retrieved by the action (example, the Id of the menuItem in question).
or you can use
new { data_customattribute="value" }
and the compiler is smart enough to know what you mean
Yes, there is an overload for ActionLink
method which takes an IDictionary<string,object>
instead of an anonymous object.
<%=Html.ActionLink("text", "Index", "Home", null /*routeValues*/, new Dictionary<string, object> { { "data-customattribute", "value" }, { "data-another", "another-value" } })%>
Outputs :
<a data-another="another-value" data-customattribute="value" href="/">text</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With