Frage

Below is my code:

default.aspx:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" 
    AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
    Inherits="TestAjax._Default" %>    

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    //I set an onClick event on this button:

    < input type = "button" id="btnCl" onclick = "doJob" />

</asp:Content>

default.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    //fires on page load;
}

void doJob()
{
    //code here;
}

The question is:

Why didn't the onclick event trigger? (On default.aspx btnCL)

Thanks

War es hilfreich?

Lösung 3

Because dojob() is a server-side function, but onclick on that input element is a client-side event. You're probably getting an error in your JavaScript console saying that dojob() is an undefined function.

Use an asp:Button instead of an input to make use of server-side click events. Also, dojob() should be protected. By not declaring a protection level I think the default is private so the page controls might not even be able to see it. It should match the event handler for a button click:

protected void dojob(Object sender, EventArgs e)
{

}

Andere Tipps

You need to use an asp:Button control like this:

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

and then have the event method like this:

protected void Button1_Click(object sender, EventArgs e)
{
    // your code here
}

When using a regular input tag, onclick is for javascript, you have to instead use the ASP.NET control asp:Button in order to hook up the C# method.

As stated in my comment in OP your current method is making a client-side call (so looking for a JavaScript function called doJob. You need to make a server-side call so need to use an <asp:Button> control. Some example of how you could achieve this:

Web-Page (.aspx)

<asp:Button ID="btnDoJob" Runat="server" Text="Do Job" OnClick="btnDoJob_Click" />

Code-Behind (.CS)

protected void btnDoJob_Click(object sender, EventArgs e)
{
    // Do your action here...
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top