Exitos
Exitos

Reputation: 29720

How do I create a class in a html block for the view I am on in MVC 3?

I have this code that is my navigation bar on my site, it is in my _layout.cshtml page at the top...

<div  id="nav">
            <ul>
                <li id="current"><a href="/home/index">Home</a></li>
                <li><a href="/code/index">Code Stuff</a></li>
                <li><a href="/music/index">Music Stuff</a></li>
                <li><a href="/blog/index">Blog</a></li>
                <li><a href="/links/index">Links</a></li>   
                <li><a href="/contact/index">Contact</a></li>   
            </ul>       
        </div>  

Im using a razor view page and I need to be able to inject id="current" into the block for the page that im on. My solution was to do something like

<div  id="nav">
            <ul>
                <li id="@Model.PageName"><a href="/home/index">Home</a></li>
                <li id="@Model.PageName"><a href="/code/index">Code Stuff</a></li>
                <li id="@Model.PageName"><a href="/music/index">Music Stuff</a></li>
                <li id="@Model.PageName"><a href="/blog/index">Blog</a></li>
                <li id="@Model.PageName"><a href="/links/index">Links</a></li>  
                <li id="@Model.PageName"><a href="/contact/index">Contact</a></li>  
            </ul>       
        </div>  

But of course that wont work because all of the li items will have the pagename in. So without using burly if statements how can I do this dynamically?

Upvotes: 2

Views: 81

Answers (1)

tvanfosson
tvanfosson

Reputation: 532595

First, you really should be using class (as indicated in your title) rather than id (as indicated in your question text). Second, I would define a function that takes an argument differentiated your link and outputs either the empty string or current depending on whether it matches the page name.

 @functions
 {
     public string MenuClass( string menuItem )
     {
         return string.Equals( Model.PageName, menuItem, StringComparison.OrdinalIgnoreCase )
                     ? "current"
                     : "";
     }
 }


 <div  id="nav">
        <ul>
            <li class="@MenuClass("Home")"><a href="/home/index">Home</a></li>
            <li class="@MenuClass("Code")"><a href="/code/index">Code Stuff</a></li>
            ...  
        </ul>       
  </div>

Upvotes: 3

Related Questions