C# code behind for Button Click Event, ASP.NET

独自空忆成欢 提交于 2019-11-29 10:57:37

You could probably get away with adding the runat="server" attribute to your buttons but I've never tried it and frankly, using proper web controls would be the best way to go.

Replacing them shouldn't change the look and feel of the page at all. Just add CssClass="xxx" to apply the css if there is any, otherwise they render to standard html elements anyway.

Your markup should look something like this:

<asp:Button runat="server" id="btnLogin" Text="Log In" OnClick="btnLogin_Click" />

The matching event handler in your code would look like this:

protected void btnLogin_Click(object sender, EventArgs e)
{
    // Here's where you do stuff.
}

you need to replace the

onclick="btnLogin_Click();"

with

onclick="btnLogin_Click"

because the onClick property of asp.net buttons need to contain the name of the function it calls in the aspx.cs file and not the actual call.

My suggestion would be to change the HTML control to <asp:Button /> and have the event handler wired up by ASP.NET. Syntax would look something like below

<asp:Button ID="Test" runat="server" Text="Button" OnClick="Test_Click" />

If you are using a tool like Visual Studio/Express bring up the page in question (the aspx page).

From the controls toolbar drag a button over to the page.

If you double click the button in design view it will automatically create the event handler in code behind.

The button control has a couple of properties OnClick and OnClientClick. Use OnClientClick to trigger any JavaScript on the page.

Hope it helps

There are ways to reach asp.net code behind handler from html controls. You could try adding onserverclick handler or you could do a postback with arguments and add handler to the postback in contructor.

Few links to help you with it:

https://forums.asp.net/t/1650304.aspx?Calling+code+behind+function+from+a+html+button

calling server side event from html button control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!