views:

52

answers:

2

I need to add class attribute to the body tag from a view file (.aspx), but the tag is in the master file. How can I access the body tag from a view?

A: 

In your view output you could just add a jQuery client script to do it which will run once your page is pieced together:

$('body').addClass('yourClass');

Another method would be to store the class data in your controller like:

ViewData["MasterPageBodyClass"] = "yourClass";

Then in your MasterPage view you could check for the existance of this and add it if it exists:

<%
    string bodyClass = "";
    if (ViewData["MasterPageBodyClass"] != null)
    {
        bodyClass = "class=\"" + ViewData["MasterPageBodyClass"].ToString() + "\"";
    }
%>
<body <%= bodyClass %>>

Only the controller actions that required the class to be attached to the body would actually need to store the class in the ViewData every other action could just ignore it.

Kelsey
A: 

think a simpler solution is just set a placeholder at the master for the class attribute:

<body class='someOtherClass <asp:ContentPlaceHolder ID="BodyCssOverrides" runat="server" />' >

then in your views just set the proper class:

<asp:Content ContentPlaceHolderID="BodyCssOverrides" runat="server">yourBodyClass</asp:Content>

no need for scripts to set it or ViewData.

remember that the masterPage is a template that should help you and not get in your way, if something needs to change between views - make a placeHolder for it

Avi Pinto