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".

5 comments:

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

    ReplyDelete
  2. b33ry: Use the 'title' attribute


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

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

    ReplyDelete
  4. 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

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

    ReplyDelete