Slinky
Slinky

Reputation: 5832

Adding a class to Html.ActionLink - ASP.NET MVC 3

I need to add a class to this link:

 @Html.ActionLink("Sign Out", "LogOff", "Account") 

But when I do this:

@Html.ActionLink("Sign Out", "LogOff", "Account",new{@class="btn blue"})  

The link points to the Home controller, not the Account controller thus throwing a 404.

/Home/LogOff?Length=7

What am I doing wrong?

Thanks

Upvotes: 4

Views: 3866

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Try using the proper overload of the ActionLink helper (yeah there are gazillions of overloads):

@Html.ActionLink(
    "Sign Out",                  // linkText
    "LogOff",                    // actionName
    "Account",                   // controllerName
    null,                        // routeValues
    new { @class = "btn blue" }  // htmlAttributes
)

whereas you were using:

@Html.ActionLink(
    "Sign Out",                    // linkText
    "LogOff",                      // actionName
    "Account",                     // routeValues
    new { @class = "btn blue" }    // htmlAttributes
)

See why your code is not working?

Yeah, Microsoft did a hell of a mess with those overload and if you are not careful you get caught into the trap.

Solution: read MSDN or use Visual Studio Intellisense (F12 while your cursor is over the ActionLink helper).

For that reason I prefer to write it in a mode explicit manner using C# 4.0 named parameters:

@Html.ActionLink(
    linkText:       "Sign Out",
    actionName:     "LogOff",
    controllerName: "Account",
    routeValues:    null,
    htmlAttributes: new { @class = "btn blue" }
)

Upvotes: 16

pinmonkeyiii
pinmonkeyiii

Reputation: 191

When calling the ActionLink, there are several overloaded functions to call this. The one you want to use is Html.ActionLink("Link Text", "Action Name", Controller", "Route Values", HTML Attributes")

So something like this: @Html.ActionLink("Sign Out", "LogOff", "Account", null, new{@class="btn blue"})

Upvotes: 1

Related Questions