How to handle the event of a home page button on a content page?

There is more than a question and an article about the same exact question, but I have a few more related questions and I hope to get answers.

  • I heard about two approaches to find a button and add a handler or use an interface (check both approaches from here ) .. Which one do you suggest?

  • If you can, please, illustrate the "Interface" option with some code and where is the class for the interface file, then it does not read on the page when I try to inherit it!

+6
source share
2 answers

The second aspect is IMO is better. The first option associates the page with a specific main page, and this is not nice.

All files are placed in one 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. For instance. You can publish an event through an event broker .

+7
source

See From My Openion would be better if you use event handlers ... and even with a custom delegate.

like this

 public delegate ReturnType MasterPageButtonHandler(CustomEventArgs ObjPriargs); public event MasterPageButtonHandler MasterPagebuttonClick; . . . . Button.click+=new EventHandler(Button1_Click); . . . protected void Button1_Click(Object sender,EventArgs e) { if(MasterPagebuttonClick!=null) { CustomEventArgs ObjPriargs=new CustomEventArgs(); ObjPriargs.Property1=SomeValu1; ObjPriargs.Property2=SomeValu2; MasterPagebuttonClick.Invoke(ObjPriargs); } } . . . public class CustomEventArgs { Public DataType Property1{get;set;} Public DataType Property2{get;set;} Public DataType Property3{get;set;} } . . . // Now in your aspx Page MyMaster m=Page.Master as MyMaster; m.MasterPagebuttonClick+=new MasterPageButtonHandler(MasterPageHandler_Click); . . . protected void MasterPageHandler_Click(CustomEventArgs ObjPriargs) { //You code///// } 

going through this method gives some flexibility, as in the case if in the future you want to transfer some page with data about the travel by data on click .. this is easily possible.

0
source

Source: https://habr.com/ru/post/886050/


All Articles