ASP.NET MVC: Use CSS on Html.ActionLink

I have seen plenty of asp.net mvc questions around applying CSS on an HTML.ActionLink, so I thought of writing a post to demonstrate how to do so.

We will use the default Site.master in a sample ASP.NET MVC application. The Menu link is declared similar to the following:

<div id="menucontainer">

<
ul id="menu">
<
li><%: Html.ActionLink("Home", "Index", "Home")%></li>
<
li><%: Html.ActionLink("About", "About", "Home")%></li>
</
ul>

</
div>

Let’s apply a css class to the ‘About’ Link. To do so, declare a style in the Site.css file as shown below. The class is called 'custom'. Note: Site.css comes by default with the VS 2010 MVC template and is in the Content folder:

customcss

We will now apply this CSS to our Html.ActionLink. Use the following code:

mvchtmlattrib

We have used an overload of the ActionLink method where we are setting the routevalues to null and the htmlAttributes to the CSS class.

image

Before

mvcactionlink

After

mvcactionlinkcss

If you right click the page and view the source code, you will see that the 'About' link is decorated with class='custom".






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

5 comments:

b33ry said...

thanks for the helpful post. How do I add a tooltip to an ActionLink?

Suprotim Agarwal said...

b33ry: Use the 'title' attribute


<%=Html.ActionLink("About", "About", "Home", null,
new {title="This is a Tooltip" }) %>

Anonymous said...

Hey there
What if you needed to decorate the menu item of the current view?

Anonymous said...

to highlight the current view, try this post

http://geekswithblogs.net/bdiaz/archive/2010/04/09/handy-asp.net-mvc-2-extension-methods-ndash-where-am-i.aspx

himanshu pareek said...

How to hide link url from Browser's status bar .(Bottom on a browser, when mouse over on a link) ?