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 calle开发者_运维百科d 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!
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)
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;
}
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.
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.
Why not encapsulate the ImageButton and it's click handler into a UserControl? Then you won't have to repeat any code.
精彩评论