Exchange event handler code between pages

How can you create event handling code in ASP.NET and share it between controls on multiple pages?

For example, two pages with

<asp:Repeater runat="server" OnItemCreated="NavigationItemCreated"> 

Instead of copying it for each page, I tried to put it in a class accessible for both pages

 <asp:Repeater runat="server" OnItemCreated="MyHelper.NavigationItemCreated"> 

The class is as follows:

 public class MyHelper { public static void NavigationItemCreated(object sender, RepeaterItemEventArgs e) { } public static string MyProperty { get; set; } } 

However, I get an error when I try to execute (happens with or without static ):

Compiler error message: CS1061: "ASP.page_default_aspx" does not contain a definition for "MyHelper" and there is no extension method "MyHelper" that accepts the first argument of type "ASP.page_default_aspx" (do you miss the use directive or assembly reference? )

I can still access MyProperty with <%# MyHelper.MyProperty %> , so MyHelper can be used by the page, not by event handlers.

Update:
Made the class and event handling code static, and it also doesn't work, doesn't put it in its own namespace and uses MyNamespace.MyHelper.NavigationItemCreated

+4
source share
3 answers

You can create a custom control or create your own class that extends the standard Repeater class. In this custom control, you implement the general OnItemCreated functions.

+1
source

It will work

  • is your MyHelper class located in APP_Code ?

  • if so, than the namespace check that you included in the default file for the page code that contains the MyHelper class definition

0
source

You can create a base page and place the event handler code there.

Then on your child page, which inherits from this base page, you can call the base page event handler method.

By doing this, you will have a central point for managing shared code! No need to change it everywhere.

0
source

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


All Articles