asp.net mvc modifying master file from a view

左心房为你撑大大i 提交于 2019-12-10 10:31:30

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3671956/asp-net-mvc-modifying-master-file-from-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!