Frage

I'm new to ASP.NET and I'm too stupid to find a solution for my problem: I'm trying to reference the onclick attribute of a button to a method defined in my C# file

ASPX file:

<!-- ... -->
<button onclick="myFunction();">
    Click me!
</button>
<!-- ... -->

C# file:

public partial class TestSite : System.Web.UI.Page {

    protected void Page_Load (object sender, EventArgs e) {}

    public void myFunction () {
        // MessageBox?
    }
}

I know that I could do this with the script tag, but my target is to seperate layout and code.

War es hilfreich?

Lösung

Create page method

[System.Web.Services.WebMethod]
public static string myFunction (string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}

And call this method in aspx as below using jquery

<button onclick="myFunction();">
    Click me!
</button>
function myFunction() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/myFunction ",
        data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top