Override ASP Master Page html in one content page?

I am using ASP Master Pages and I would like to add an onkeypress event handler in <body>

the master page, but only for one page.

How to do it?

+2


a source to share


2 answers


I would add a public property to the MasterPage, something like BodyOnKeyPress

. Then set the OnKeyPress attribute of the body tag in the MasterPage PreRender event. Client pages just need to set this property before the Master PreRender event occurs.

This is aerial code as I don't have a project to test. But it should be something like this:

MasterPage markup:



<%-- Mark the body tag with runat="server", and give it an ID to reference in code. --%>
<body id="mainBody" runat="server">
    ...
</body>

      

MasterPage CodeBehind:

protected void Page_PreRender(...) {
    mainBody.Attributes["onkeypress"] = this.BodyOnKeyPress;
}

public string BodyOnKeyPress {
    get {
        return ViewState["BodyOnKeyPress"];
    }
    set {
        ViewState["BodyOnKeyPress"] = value;
    }
}

      

+1


a source


Can also be done with a script in the content of this page ... I will use jQuery to simplify the idea



<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript">
    $(function () {
        $(document.body).keypress(function(){});
    });
</script>

</asp:Content>

      

+1


a source







All Articles