2

I'm wondering how I can change the class that is assigned to an element in the layout view from the C# code within the controller?

In my nav bar I have a css class that is set as active when viewing the page but obviously I need to change this when I change views (pages) but i'm not sure on the best way to do this within mvc

1
  • How are you generated the HTML element? Commented Oct 18, 2015 at 18:28

3 Answers 3

1

Attempt to bind CSS values to model or viewbag

for example

@Html.TextBoxFor(model => model.Value1, new { @class = ViewBag.value1Class })

or may be

<div class="@Model.Class1 @Model.Class2"/>
Sign up to request clarification or add additional context in comments.

Comments

1

You can inspect the current controller name and action as detailed in this post and use that information in your layout to choose which element should be "active".

Or in a simple application another common way to do this is to use the ViewBag and set a property with the name of the current page.

In your controller method include the following.

ViewBag.CurrentPageName = "HomePage";

Your Razor (MVC3+) view code can consume this information and set the appropriate class on an element.

@{
  string pageName = ViewBag.CurrentPageName ?? "Unknown";
}

if(pageName == "HomePage"){
   //Output your DOM element with the appropriate class name for the "active" link.
}

OR

<a href="#" class="@(pageName == "HomePage" ? "active" : string.Empty)>Home Page</a>

For MVC2 and older you'll need to use TempData, but the concept is similar.

Comments

0

Use jquery maybe?

$( document ).ready(function() {
    $("#mainPageDiv").removeClass()
                     .addClass('newClass'); 
});

Put this in view, not layout.

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.