Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC razor - add class to shared layout parent div from a child view

I'm in the (not entirely unusual) situation of having a containing div in my shared layout:

<div class="main-content">
    ** views are rendered here in a fixed width container **
</div>

Usually this is fixed width but on certain pages I'd like to add the class "fullwidth" to this container which allows it to fill the entire page width. In this specific case it's because the view will host a Javascript application which requires a large workspace.

I could do this with jQuery but I don't want it to happen after the page has rendered, ideally Razor could append this class to the container.

Is there any way for me to affect the content of a shared layout from within a view? renderSection feels quite close to what I need but it would be quite insane to define a section within a class attribute just to append one class name to it, similarly duplicating the shared layout would be overkill...

Is there a way of doing this?

Thanks

like image 383
managedheap84 Avatar asked Sep 27 '13 15:09

managedheap84


1 Answers

I've used this approach in a similar situation:

In _Layout.cshtml:

<body class="@RenderSection("BodyCssClass", false)">

In any views which need to override the body's CSS class:

@section BodyCssClass {@Html.Raw("full-width")}

This seems like overkill for such a simple thing, but it avoids using the ViewBag, which is a good thing in my book.

like image 110
Nugsson Avatar answered Oct 06 '22 16:10

Nugsson