Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 200
Jeff Camera Avatar asked Nov 20 '10 22:11

Jeff Camera


People also ask

What is ASP.NET MVC in C#?

Model View Controller (MVC) MVC is a design pattern used to decouple user-interface (view), data (model), and application logic (controller). This pattern helps to achieve separation of concerns.

Is C# and ASP.NET MVC are same?

They are the same thing. C# is the language you have used to do your development, but ASP.NET MVC is the framework you used to do it.

Is ASP.NET MVC still used?

It is no longer in active development. It is open-source software, apart from the ASP.NET Web Forms component, which is proprietary. ASP.NET Core has since been released, which unified ASP.NET, ASP.NET MVC, ASP.NET Web API, and ASP.NET Web Pages (a platform using only Razor pages).

What is .NET ASP.NET and C#?

Basically, ASP.NET is a web delivery mechanism that runs either C# or VB.NET in the background. C# is a programming language that runs ASP.NET as well as Winforms, WPF, and Silverlight.


1 Answers

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.

like image 69
Darin Dimitrov Avatar answered Nov 01 '22 23:11

Darin Dimitrov