开发者

Button not picking up c# code behind event, what did I do wrong?

开发者 https://www.devze.com 2022-12-11 20:13 出处:网络
I have a button: <button type=\"submit\" class=\"contact\" onclick=\"click\"> and I have a c# code behind function:

I have a button:

<button type="submit" class="contact" onclick="click">

and I have a c# code behind function:

protected void click(object sender, EventArgs e)
{
    contact_label.Text = "tester";
}

and there is a label on my page:

<asp:La开发者_JS百科bel id="contact_label"...

The trouble is when I click the button the 'click' function is not being called, why not? How do I remedy it?


you need a runat=server

try this:

<asp:button id="button" runat="server" onclick="click" cssclass="contact">

If you don't want to use the asp:button

<button id="button" runat="server" OnServerClick="click" >

Here is an article explaining it: http://ondotnet.com/pub/a/dotnet/2001/06/21/webforms.html?page=2

If you don't want to use a server side button at all, you could on the page_load event check which button did the submit action (through the request.form). You won't have an object to call the event handler, but you could but the code in another method and perform the same action.


You need a bit more then just runat="server", you need to:

  1. Choose to use an ASP.NET asp:Button class (as opposed to standard HTML)
  2. Add runat="server"
  3. Remove the non-relevant HTML code:

This is automatically also a submit button:

<asp:Button
     CssClass="contact" 
     runat="server" 
     OnClick="click" 
     Text="Hello World" />

C# will now be called:

protected void click(object sender, EventArgs e)
{
    contact_label.Text = "tester";
}

EDIT: Kevin showed how this can be done for default HTML controls and also explained how you can create additional "events" by using a switch-statement in your Page_Load. I misunderstood the question originally, I'll leave my answer for people wanting to work with ASP.NET controls.

0

精彩评论

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

关注公众号