Omer Omer - 7 days ago 7
ASP.NET (C#) Question

Call a Javascript function from aspx

Code from aspx.cs:

.......
button.OnClientClick = "onButtonClick(this)";
.....


Function in Javascript(written in the aspx file):

<script>
function onButtonClick(event) {
....
}
</script>


The "program" didn't even get to the script.

Answer

Where are you calling your button.OnClientClick assignment? If it is in the page load or a button click event, it should work. If you are calling it in an ajax method, the button may be be rendered after the assignment, so maybe that's your problem.

protected void Page_Load(object sender, EventArgs e)
{
    Button1.OnClientClick = "clicky(this)";
}

On .aspx page, just before the closing tag:

<script>
   function clicky(e) {
      alert("click");
   }
</script>

You should be able to see onclick="clicky(this)"; when you inspect the element in the Chrome developer tools when you run the page.

Comments