Pass MasterPage ImageButton event to content Page

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 01:08:12

问题


I have ImageButton in a MasterPage. I want the OnClick event to fire and be captured by the .ASPX page hosted inside the MasterPage?

MasterPage:

<asp:ImageButton ID="btnClear" OnClick="Clear_Click" 
 ImageUrl="images/Back_Icon_06.png" runat="server" AlternateText="Clear" 
 width="38"   height="39"/>

回答1:


The masterpage is actually a child of the page (in fact, it's a UserControl). We don't want the page to have to be aware of the intimate details of its child controls (thats why we delegate those aspects to those controls in the first place), so the correct approach would be to handle the click event on the master page and from there fire another event on the masterpage which the page handles:

Master:

public event EventHandler SomethingHappened;

protected void Button_Click(object sender, EventArgs e)
{
    OnSomethingHappened(EventArgs.Empty);
}

protected void OnSomethingHappened(EventArgs e)
{
    if(this.SomethingHappened != null)
    {
        this.SomethingHappened(this, e);
    }
}

Page:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    //allows us to change master pages
    if(this.Master is MyMaster)
    {
        ((MyMaster)this.Master).SomethingHappened += new EventHandler(HandleSomethingHappened);
    }
}

private void HandleSomethingHappened(object sender, EventArgs e)
{
    //deal with it
}



回答2:


I would recommend specifying a strongly typed master page in your content page and exposing the event on the master page side

Here's a good MSDN reference

This is similar to what Rex M specified but just simplifies accessing the Master Page a little bit.

// Master Page Code
public event EventHandler ClearClick
{
   add
   {
      this.btnClear.Click += value;
   }
   remove
   {
      this.btnClear.Click -= value;
   }
}

// Content Page markup
<%@ Page  masterPageFile="~/MasterPage.master"%>

<%@ MasterType  virtualPath="~/MasterPage.master"%> 

// Content Page Code
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    this.Master.ClearClick += new EventHandler(OnClearClick);
}

private void OnClearClick(object sender, EventArgs e)
{
   // Handle click here
}


来源:https://stackoverflow.com/questions/1569591/pass-masterpage-imagebutton-event-to-content-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!