How to change body class on MVC3 watch page

Just wanted to add

in the <tag>. Is there any html helper or something else on the MVC3 view page? Please advise, thanks.
+7
source share
2 answers

This is very similar to Aaron's solution, but does not have a section weight (at least, in my opinion, for larger blocks of content than one line). The easiest way is to pass the variable using the ViewBag.

In your layout just print the class for the body tag, as well as any other page variables (page name, additional css / js scripts, etc.)

_Layout.cshtml:

<html> <title>@ViewBag.Title</title>@* Can easily add in per page titles too *@ <body class="@ViewBag.BodyClass"> @RenderBody() </body> </html> 

Then the variables set in your view are passed up the layout:

Index.cshtml:

 @model MyViewModel @{ ViewBag.Title = "This page title!"; ViewBag.BodyClass = "..."; } 
+16
source

While you could have full control over the HTML, the solution was what was needed, so here is one :-)

On the _layout.cshtml page

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

This will look for a section on all child pages, but says don’t worry if it cannot find one

Then in your child’s views just do it

 @section BodyClass {productList} 

Keep it on one line and then the HTML output will look great, also you can also create class names.

 @section BodyClass {productList generic} 

This idea fits perfectly with the specific DOM-Ready page code, why not check out http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/

Or my extended version is here https://github.com/AaronLayton/H5BP-Core

My method allows you to do page code, but allows you to store all Javascript on separate pages so that each page becomes easily manageable. The final step would be to merge and minimize all JS into 1 file; -)

+15
source

All Articles