Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting an ID on <body> in ASP.NET MVC

I would like my views to be able to specify a class for the <body> tag, which lies in my master page.

My first take was to do something like this:

<asp:Content ContentPlaceHolderID="BodyClassContent" runat="server">
    view-item</asp:Content>

However, that would require this in the master page, which doesn't work:

<body class="<asp:ContentPlaceHolder ID="BodyClassContent" runat="server" />">

Any solutions to this?

like image 906
Guðmundur H Avatar asked Oct 18 '25 14:10

Guðmundur H


2 Answers

In the layout you can do this on the body tag:

<body @RenderSection("BodyAttributes", false)>

and then in your view you can do this:

@section BodyAttributes {
    id="login" class="login"
}

Edit: I also had to do this working with VB.NET and WebForms today and found a handy link for achieving the equivalent

like image 176
DevDave Avatar answered Oct 21 '25 02:10

DevDave


I would suggest a different approach.

You create an hierachy of view models, starting with the MasterModel. When you instantiate a view object, you pass a body class to it.

public class MasterModel
{
    string BodyCss { get; set; }

    public MasterModel (string bodyCss)
    {
        BodyCss = bodyCss;
    }
}

public class MyView1Model : MasterModel
    : base ("body-view1")
{
}

Then in your master view which should be strongly typed to MasterView:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<MasterModel>" %>

you just write:

<body class="<%= Model.BodyCss %>"></body>