简体   繁体   中英

Programatically added HTML Button - OnServerClick doesn't work

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<html>
    <head>
        <title>Test Case</title>
    </head>
    <body>
        <div id="testdiv" runat="server"></div>
    </body>
</html>

Default.aspx.cs:

using System;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        testdiv.InnerHtml = "<input type=\"button\" runat=\"server\" OnServerClick=\"Test_Click\"/>";
    }

    protected void Test_Click(object sender, EventArgs e)
    {
        testdiv.InnerHtml = "REGISTERED CLICK!";
    }
}

I want Test_Click to be run on the server when the button is clicked, but it doesn't.

I tried putting it in a server side form, but it still doesn't work.

try this way,

protected void Page_Load(object sender, EventArgs e)
{
    var button = new Button {ID = "Button1", Text = "Test Button"};
    button.Click += button_Click;
    PlaceHolder1.Controls.Add(button);
}

private void button_Click(object sender, EventArgs e)
{
    testdiv.InnerHtml = "Button1 is clicked";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM