且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理在内容页母版页按钮事件?

更新时间:2023-02-02 19:48:14

二是形式给出更好的IMO。第一种选择的夫妻一个页面的特定母版页,这是不是很好。



所有的文件都放在同一个文件夹中。



IPageInterface.cs:

 命名空间CallFromMasterPage 
{
公共接口IPageInterface
{
无效DoSomeAction();
}
}



Default.aspx.cs:

 命名空间CallFromMasterPage 
{
公共部分类默认:System.Web.UI.Page,IPageInterface
$ { b $ b酒店的公共空间DoSomeAction()
{
抛出新NotImplementedException();
}
}
}



Site.Master.cs:

 命名空间CallFromMasterPage 
{
公共部分类SITEMASTER:System.Web.UI.MasterPage
{
保护无效的button1_Click(对象发件人,EventArgs五)
{
IPageInterface pageInterface =页面为IPageInterface;
如果(pageInterface!= NULL)
{
pageInterface.DoSomeAction();
}
}
}
}

有其他的方法。例如。您可以通过发布事件代理的事件。


There's more than question and article about the same exact question but I have a couple more related questions and was hoping to get some answers.

  1. I've heard of two approaches to find the button and add the handler or use an interface (Check both approaches from here) .. Which one do you suggest ?

  2. If you could please illustrate the 'Interface' option with some code and where to class the interface file cause it's not readable in the page when I try to inherit it!

Second aproach is IMO better. The first choice couples a page to the specific master page, and it is not nice.

All files are placed in the same folder.

IPageInterface.cs:

namespace CallFromMasterPage
{
    public interface IPageInterface
    {
        void DoSomeAction();
    }
}

Default.aspx.cs:

namespace CallFromMasterPage
{
    public partial class Default : System.Web.UI.Page, IPageInterface
    {
        public void DoSomeAction()
        {
            throw new NotImplementedException();
        }
    }
}

Site.Master.cs:

namespace CallFromMasterPage
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        protected void Button1_Click(object sender, EventArgs e)
        {
            IPageInterface pageInterface = Page as IPageInterface;
            if (pageInterface != null)
            {
                pageInterface.DoSomeAction();
            }
        }
    }
}

There are other approaches. E.g. you can publish an event via event broker.