Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify body class in MVC3 view page

Just wanted to add a class="myClass" in body tag. Is there any html helper or something else can do this in MVC3 view page? Please advise, thanks.

like image 441
Stan Avatar asked Jun 11 '11 00:06

Stan


People also ask

Can you use C# code in your views?

Generally, you can put your c# code wherever you want. The only conventions that MVC adheres to by default are the Controllers and Views folder.

How do I change the default layout in MVC?

The _ViewStart. cshtml can also be created in the sub-folders of the View folder to set the default layout page for all the views included in that particular subfolder. For example, the following _ViewStart. cshtml in the Home folder sets the Layout property to _myLayoutPage.

What is@ section in Razor?

@section is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).

What is view class MVC?

A view is an HTML template with embedded Razor markup. Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup.


1 Answers

This is very similar to Aaron's solution, but doesn't have the weight of a section (which at least in my mind, are for larger blocks of content than a single string). The simplest way is to pass a variable with the ViewBag.

In your layout, just print out the class for the body tag, plus any other page specific variables (page title, extra 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, variables set in your view get passed upwards to the layout:

Index.cshtml:

@model MyViewModel
@{
    ViewBag.Title = "This page title!";
    ViewBag.BodyClass = "...";
}
like image 71
Leniency Avatar answered Oct 22 '22 06:10

Leniency