views:

221

answers:

5

I have a site with a master page, Site.master. Many of Site.master's content pages have the same button that functions the same way on each page:

<asp:ImageButton ID="btn" runat="server" OnClick="btn_Click" />

Is it possible to write btn_Click once in Site.master's CodeFile and have it called in the OnClick attribute of each content page's button? I'm trying to avoid adding the same function (or anything at all) to each content page's CodeFile.

Thanks!

+1  A: 

You can, but it's not pretty. A better way is to make your content pages derive from a common base class that inherits from Page. There you can put code that's common to all pages.

Lette
+2  A: 

If the buttons are pretty much identical, you could just put them into the Master page (or a SubMaster page).

Otherwise, with MasterType you can strong type the Page.Master property. It may be possible to wire up a button like:

<asp:ImageButton ID="btn" runat="server" OnClick="Master.btn_Click" />

If not, you could have the Master search for a control with a known ID and hook it up.

public string ButtonId { get; set; }

override OnLoad(EventArgs e) {
   var b = Page.FindControl(this.ButtonId ?? "btn") as Button;
   if (b != null) b.Click += this.On_Click;
}
Mark Brackett
I was pretty sure I tried using MasterType before without success, but tried it again and it worked. Sure it's not the best practice, but it worked in a pinch. Thanks!
ovinophile
+3  A: 

It's doable, but as a best practice you'll save yourself a lot of heartache if you just make a conscious choice to keep as much functionality out of your master pages as possible. Reserve them for presentation and presentation alone. You might be better served using base page classes and user controls to perform actions at the page level (especially if it is a universal action)

Joel Etherton
I was about to suggest user controls for this.
Zhaph - Ben Duguid
+1  A: 

If the button is on every page, is there some reason not to actually put the button in the Master?

If this isn't possible, I would recommend creating a new class file (e.g., FooButtonBehavior) then put your button handler in that class (e.g., OnFooClicked()). Then in your code-behind for each class just new up an instance of FooButtonBehavior and call OnFooClicked(). If you need to pass in any controls that get manipulated on the page, you can do that as well.

DanM
+1  A: 

Why not encapsulate the ImageButton and it's click handler into a UserControl? Then you won't have to repeat any code.

Nick Higgs