Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 759
Slinky Avatar asked Dec 03 '22 22:12

Slinky


1 Answers

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" }
)
like image 178
Darin Dimitrov Avatar answered Dec 27 '22 11:12

Darin Dimitrov