Tuesday, October 17, 2017

Adding attributes to the <body> tag when using Master Pages

roblem

If you are using Master Pages in an ASP.NET application and you need to add an attribute to the <BODY> tag from a Content Page -- for instance, to set a client script function for the onload event of the page -- you will find that you can't do it directly because the <BODY> tag is in the Master Page, not in your Content Page.

Solution

Make the <BODY> tag on the Master Page a public property, so you can access it from any Content Page. First, promote the <BODY> tag in the Master Page to an ASP.NET server control. Change:
<BODY>
to:
<BODY id="MasterPageBodyTag" runat="server">
Now that the body tag is a server control, you can configure access to it as a public property in the Master Page code behind file:
using System.Web.UI.HtmlControls;
public partial class MyMasterPage : System.Web.UI.MasterPage
{
    public HtmlGenericControl BodyTag
    {
        get
        {
            return MasterPageBodyTag;
        }
        set
        {
            MasterPageBodyTag = value;
        }
    }
...
Note that the MasterPageBodyTag server control is of type System.Web.UI.HtmlControls.HtmlGenericControl. To demonstrate this, just set a breakpoint in the Page_Load function in the code behind file, run the ASP.NET project in debug mode to that point, and execute ?MasterPageBodyTag.GetType().ToString() in the Immediate Window. To use this property from a Content Page, first declare the type of your Master Page in your Content Page's ASPX file:
<%@ MasterType TypeName="MyMasterPage" %>
Then somewhere in your Content Page's code behind file, use the Master Page's BodyTag property to add an attribute to the <BODY> tag:
protected void Page_Load(object sender, EventArgs e)
{
    Master.BodyTag.Attributes.Add("onload", "SayHello()");
...
This example, of course, assumes that there is a SayHello() client script in this Content Page. Running the application to the Content Page and then viewing the source code in the browser will show that the onload="SayHello()" attribute was added to the <BODY> tag. This technique should work for any HTML tag in the Master Page that you wish to access from a Content Page.

Source : https://www.codeproject.com/Articles/19386/Adding-attributes-to-the-lt-body-tag-when-using-Ma

No comments:

Post a Comment