user1865044
user1865044

Reputation: 301

How to edit a CSS class in the MVC Layout view using C#

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

Upvotes: 2

Views: 2130

Answers (3)

onedevteam.com
onedevteam.com

Reputation: 4178

Use jquery maybe?

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

Put this in view, not layout.

Upvotes: 0

BenM
BenM

Reputation: 121

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.

Upvotes: 1

Karan Bhandari
Karan Bhandari

Reputation: 506

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

Upvotes: 1

Related Questions