-2

I have an html list to which I am trying to add html button to the property "innerhtml" using the code behind file. I am able to add the button however the onclick event is not getting fired

HTML:

<ul runat="server" id="list">
    <li></li>
    <li><a  id="loginID" runat="server" href="../Accounts/login.aspx">Login</a></li>
    <li id="logout" runat="server"> <a href="~/Register.aspx" runat="server"> Register</a></li>    
</ul>

code behind:

logout.InnerHtml = "<input type=\"submit\" id=\"b1\" runat=\"server\" onserverclick=\"b1_click\" />"; //logout is the id of the list item             
         }
    }

    public void b1_click(Object sender,EventArgs e)
    {
        Response.Redirect("~/Accounts/login.aspx");
    }
}
MarmiK
  • 5,639
  • 6
  • 40
  • 49
  • Take a look at http://stackoverflow.com/questions/4830095/asp-net-button-onserverclick-only-works-when-onclick-isnt-defined, maybe it can be useful to you. – PhoneixS Apr 18 '17 at 10:54
  • Possible duplicate of [Inserting HTML elements with JavaScript](http://stackoverflow.com/questions/814564/inserting-html-elements-with-javascript) – Woodrow Barlow Apr 18 '17 at 20:24

1 Answers1

0

This isn't the right way to dynamically create server-side controls. Please review the example below to get a better understanding of how to do so. Keep in mind you can not assign the ClientID property as it is read only and initialized during runtime.

protected void Page_Load(object sender, EventArgs e)
{
    Button btn = new Button();
    btn.Text = "Dynamic Button";
    btn.ID = "b1"; // Server Side ID
    btn.Click += b1_click;

    logout.Controls.Add(btn);
}

public void b1_click(Object sender,EventArgs e)
{
    Response.Redirect("~/Accounts/login.aspx");
}
Tommy Naidich
  • 752
  • 1
  • 5
  • 23