3

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?

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.