Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create an ActionLink with HTML 5 Data- attributes?

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?

like image 850
AaronSieb Avatar asked Feb 26 '10 02:02

AaronSieb


People also ask

What is HTML ActionLink ()?

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.

What is data attribute in html5?

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.

What is difference between HTML ActionLink and URL action?

Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.

How do I pass an object in ActionLink?

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).


2 Answers

or you can use

new { data_customattribute="value" }

and the compiler is smart enough to know what you mean

like image 172
Nadeem Khedr Avatar answered Oct 04 '22 06:10

Nadeem Khedr


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> 
like image 25
Çağdaş Tekin Avatar answered Oct 04 '22 04:10

Çağdaş Tekin