kalu
kalu

Reputation: 337

Html in Razor MVC 3

How can I write this in MVC 3 Razor correctly?

<li  <%if(ViewContext.RouteData.Values["Controller"].ToString() == "Home"){%> class="active"<%} %>><a href="@Url.Action("index", "Home")">Home</a></li>

Blessings

EDIT

this is my code and does not work :(

<div class="navbar">
 <div class="navbar-inner">
   <div class="container">
    <a class="brand" href="#">CYSAC 2.0</a>
        <ul class="nav">
            <li @(ViewContext.RouteData.Values["Controller"].ToString() == "Home" ? "class=\"active\"" : string.Empty)><a href="@Url.Action("index", "Home")">Inicio</a></li>
            <li @(ViewContext.RouteData.Values["Controller"].ToString() == "University" ? "class=\"active\"" : string.Empty)><a href="@Url.Action("index", "University")">University</a></li>
            <li @(ViewContext.RouteData.Values["Controller"].ToString() == "Estudent" ? "class=\"active\"" : string.Empty)><a href="@Url.Action("index", "Estudent")">Estudent</a></li>

        </ul>
  </div>
 </div><!-- /navbar-inner -->
</div><!-- /navbar -->

please help

Upvotes: 0

Views: 1203

Answers (3)

Mate
Mate

Reputation: 5274

Today I found myself in the same situation ( 5 months later ).

1) Define variable controllerName and set with controller name .ToLower()

2) Compare with Equals("home")

    @{ 
        var controllerName = ViewContext.RouteData.Values["Controller"].ToString().ToLower(); 
    }
    <div class="navbar">
     <div class="navbar-inner">
       <div class="container">
        <a class="brand" href="#">CYSAC 2.0</a>
            <ul class="nav">
                <li class="@(controllerName.Equals("home") ? "active" : "")"><a href="@Url.Action("index", "Home")">Inicio</a></li>
                <li class="@(controllerName.Equals("university") ? "active" : "")"><a href="@Url.Action("index", "University")">University</a></li>
                <li class="@(controllerName.Equals("estudent") ? "active" : "")"><a href="@Url.Action("index", "Estudent")">Estudent</a></li>

            </ul>
      </div>
     </div><!-- /navbar-inner -->
    </div><!-- /navbar -->

Works for me!

Upvotes: 0

mnemosyn
mnemosyn

Reputation: 46281

You can use the @(expression) - syntax:

<li class="@((ViewContext.RouteData.Values["Controller"].ToString() == "Home" ?
           "active" : string.Empty)">
    <a href="@Url.Action("index", "Home")">Home</a>
</li>

Upvotes: 0

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

I would write this as:

<li class="@ViewContext.RouteData.Values["Controller"].ToString() == "Home" ? "active" : """>
    <a href="@Url.Action("index", "Home")">Home</a>
</li>

This has a drawback of having an class="" if it's not the current controller, but in the newest version of Razor, it will recognize this and strip it out.

Upvotes: 1

Related Questions