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:
- Choose to use an ASP.NET asp:Button class (as opposed to standard HTML)
- Add runat="server"
- 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.
精彩评论