22

I just wanna find out if there's a way to put my onClick event inside .cs:

<button type="submit" runat="server" id="btnLogin" class="button" onclick="btnLogin_Click();">

where Login_Click() should be inside .cs:

protected void btnLogin_Click(object sender, EventArgs e)
{
    // do something
} 

Please do take note that I will not use ASP.NET button here, and that I will not put my Login_Click() event inside .html/.aspx so I can't 'expose' my codes. Any suggestions?

abramlimpin
  • 5,027
  • 11
  • 58
  • 97

5 Answers5

35

You can do that on any server control and this button is made a server control by defining "runat=server". The problem is probably in your definition of the event:

<button ... runat="server" ... onServerClick="btnLogin_Click" />

You don't need "();" there...

Apart from that can you explain why you don't use the <asp:Button> here because I don't really see a problem with that...

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Koen
  • 3,626
  • 1
  • 34
  • 55
  • 1
    It looks like he already made it a `runat="server"` in the example provided. – Roman Jul 02 '10 at 16:01
  • 1
    R0MANARMY is right, you need the "OnServerClick" event for HtmlButton. Updated my example... – Koen Jul 02 '10 at 16:03
  • A common reason to use HTML button tag instead of the asp control is that asp renders the ids of the controls while in the common button tag you have more control about it. – Ivan Rascon Mar 09 '19 at 00:53
19

You'll want to use the onServerClick. There's an example of how to do that on MSDN:

<button id="Button1" OnServerClick="Button1_OnClick" runat="server">
    Click me!
</button>


protected void Button1_OnClick(object Source, EventArgs e) {
    // secret codes go here
}
droidev
  • 7,352
  • 11
  • 62
  • 94
Roman
  • 19,581
  • 6
  • 68
  • 84
5

btnLogin.Click += new EventHandler( btnLogin_Click );

will assign the btnLogin_Click event handler to the button's Click event.

however, I would point out that assigning a handler in the markup of the aspx page does not "expose your codes", as the HTML rendered down to the client doesn't have any of that information in it.

Dave Thieben
  • 5,388
  • 2
  • 28
  • 38
0

I know it's late but i lost so much time on this problem. I was setting InnerHtml of a div with buttons. You need to add type="submit" to your button if you want it to work.

milk2go
  • 159
  • 6
0

It's late but for someone out there: Apply UseSubmitBehavior="False". Example

<button type="submit" runat="server" UseSubmitBehavior="False" type="button" id="btnLogin" class="button" onclick="btnLogin_Click();">
H. Grewal
  • 41
  • 4