ActionLink htmlAttributes with hyphens
Asked Answered
L

3

89

This works

<a href="@Url.Action("edit", "markets", new { id = 1 })" 
            data-rel="dialog" data-transition="pop" data-icon="gear" class="ui-btn-right">Edit</a>

But this doesn't. Why?

@Html.ActionLink("Edit", "edit", "markets", new { id = 1 }, new {@class="ui-btn-right", data-icon="gear"})

It seems you can't pass something like data-icon="gear" into htmlAttributes?

Suggestions?

Lifework answered 5/11, 2010 at 18:32 Comment(0)
U
207

The problem is that your anonymous object property data-icon has an invalid name. C# properties cannot have dashes in their names. There are two ways you can get around that:

Use an underscore instead of dash (MVC will automatically replace the underscore with a dash in the emitted HTML):

@Html.ActionLink("Edit", "edit", "markets",
      new { id = 1 },
      new {@class="ui-btn-right", data_icon="gear"})

Use the overload that takes in a dictionary:

@Html.ActionLink("Edit", "edit", "markets",
      new { id = 1 },
      new Dictionary<string, object> { { "class", "ui-btn-right" }, { "data-icon", "gear" } });
Uxorious answered 5/11, 2010 at 22:35 Comment(4)
The underscore does not seem to work with Ajax.ActionLink helpersBraille
The underscore trick sounds really strange, what if you want an underscore in your html attribute?Toothpaste
@MichielReyers you could use the overload that takes in the DictionaryUxorious
.net Core Tag Helpers destroy all these problems - hi from the future.Bennion
P
27

Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:

@Html.ActionLink("Edit", "edit", "markets",
    new { id = 1 },
    new {@class="ui-btn-right", data_icon="gear"})

becomes:

<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>
Parsaye answered 22/12, 2011 at 6:50 Comment(0)
C
-6
@Html.ActionLink("display name", "action", "Contorller"
    new { id = 1 },Html Attribute=new {Attribute1="value"})
Cleveite answered 18/8, 2016 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.