views:

49

answers:

5

I'm trying to use the OnClick callback to call a C# function, however javascript throws an error saying the function is undefined (even though it is in the C# code).

This only happens if I add the control via Controls.Add in the page_load of the C# call behind section.

In other words if I do this (in the Page_Load function):

        LinkButton l = new LinkButton();
        l.Text = "Test";
        l.ID = "TestID";
        l.Attributes.Add("OnClick", "LinkButton_Click");
        l.Attributes.Add("runat", "server");
        l.Page = Page;
        this.Controls.Add(l);

LinkButton_Click is not defined according to javascript, however if I do this:

In the ascx file it runs fine anda ctually calls the C# function.

+1  A: 

Attribute.Add emits to the HTML, not to the aspx, so you are telling it that there should be a javascript function called LinkButton_Click() to handle the on click event.

To attach an event to a c# object, the following is the correct syntax:

LinkButton l = new LinkButton();
l.Text = "Test";
l.ID = "TestID";
l.Click += LinkButton_Click; // <-- this row attaches the event
this.Controls.Add(l);
SWeko
+8  A: 

Event handlers should be attached on the server side:

LinkButton l = new LinkButton();
l.Text = "Test";
l.ID = "TestID";
l.Click += LinkButton_Click;
l.Page = Page;
this.Controls.Add(l);

When you use the Attributes property you are actually attaching a client side function which doesn't exist.

Darin Dimitrov
+2  A: 

The problem is that when you define the LinkButton via markup, the OnClick attribute gets interpreted as part of the Server Side control.

When you add the OnClick attribute via code-behind, you're defining client-side attributes (which don't get processed at all by the server).

If you really want to define this event handler via code-behind, you need to remove the following line:

l.Attributes.Add("OnClick", "LinkButton_Click");

And replace it with:

l.Click += LinkButton_Click;
Justin Niessner
+1  A: 

The way you're adding it is adding the attribute to the html. What you need to do is add an eventhandler l.Click += new EventHandler...

Oliver
+1  A: 

You need to add the event handler to l.Click, not in the attributes.

CrazyDart