views:

59

answers:

2

Hi,

I'm using ASP Master pages, and I would like to add an "onkeypress" event handler to the <body> in the Master page, but only for a single page.

How do I do this?

Obiwanke-stackoverflow, you're my only hope.

-Alan

+1  A: 

I would add a public property to the MasterPage, something like BodyOnKeyPress. Then set the OnKeyPress attribute of the body tag in the MasterPage's PreRender event. Client pages just need to set this property before the Master's PreRender event fires.

This is air code, as I don't have a project to test on. 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;
    }
}
AaronSieb
Okay, this sounds like a workable solution. Could you give a pointer to what the code in the PreRender event might look like? I think I can figure out the rest of the stuff (I'm a ASP Masterpages newbie).
Alan
@Alan -- I've updated my answer with an example. It's air code, but it should show the basic structure.
AaronSieb
air code, I like that.
Alan
+1  A: 

Could also be done with a script in the content of that page... I will be using 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>
BrunoLM