1

I am working on an MVC4 Application

I have a following Menu Items

<ul class="menu left">
                <li>@Html.ActionLink("Home", "Index", new { Controller = "Home" }, new { @class = "active" })</li>
                <li>@Html.ActionLink("About Us", "About", new { Controller = "Home" })</li>
                <li>@Html.ActionLink("Services", "Services", new { Controller = "Home" })</li>      
                <li>@Html.ActionLink("Post Job", "Create", new { Controller = "JobPosting" })</li>
                <li>@Html.ActionLink("Job Search", "Index", new { Controller = "JobPosting" })</li>
                <li>@Html.ActionLink("Contact Us", "Contact", new { Controller = "Home" })</li>
           </ul>

Now I want if I click on Items other than Home, its css-class changes to active. Basically I just want to change the color of the menu-item How can I make this dynamically?

2 Answers 2

3

If you want to change the css based on Action or Controller you can use

@{
    var controller = ViewContext.RouteData.Values["Controller"].ToString();
    var action = ViewContext.RouteData.Values["Action"].ToString();
}

<li> 
    @if (action == "Home") { 
       @Html.ActionLink("Home", "Index", new { Controller = "Home" },new {@class="active" })
    }
    else {
       @Html.ActionLink("Home", "Index", new { Controller = "Home" })
    }
</li>
<li>
   @if (action == "About Us") { 
           @Html.ActionLink("About Us", "About", new { Controller = "Home" },new {@class="active" })
        }
        else {
           @Html.ActionLink("About Us", "About", new { Controller = "Home" })
        }
</li>

etc...

Sign up to request clarification or add additional context in comments.

3 Comments

this works but it is bad. too much logic in view and code duplication
yeah it is was just showing him how it can be done should be refactored
Thanks K.A.G , It did the trikc
0
public static class MyHtmlHelper
{
    public static String NavActive(this HtmlHelper htmlHelper, 
                          string actionName, 
                          string controllerName)
    {
        var controller = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
        var action = htmlHelper.ViewContext.RouteData.GetRequiredString("action");

        if (controllerName == controller && action == actionName )
            return "active";
        else
            return String.Empty;
    }
}

Then you can use this helper in your view.

@Html.NavActive("Index", "Home")

For instance,

<li>
    <a href="~/Home/Index" class="@Html.NavActive("Index", "Home")">
        <span>Index</span>
    </a>
</li>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.