Reputation: 11988
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?
Upvotes: 4
Views: 2609
Reputation: 6898
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
Upvotes: 7
Reputation:
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>
Upvotes: 5
Reputation: 105
You could also specify the body id attribute in the View which wishes to set it:
@{
ViewBag.Title = "Test";
ViewData["BodyID"] = "test";
Layout = "~/Views/Shared/_Layout.cshtml";}
This helps to decouple the view from the controller, the controller (and/or view model) does not need to know about the id attribute of the body tag.
Set the id of the body tag in the master page like so:
<body id="@ViewData["BodyID"]">
Upvotes: 5
Reputation: 24182
Why don't you do in your masterpage:
<body class="<%=ViewData["bodyClass"].toString()%>">
and then set ViewData["bodyClass"] in your Controller actions? That should be equivalent...
Upvotes: 4