开发者

OnClick callback thinks it's a javascript function?

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 开发者_JAVA百科= "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.


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.


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;


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);


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...


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜