Prop Webcontrol Button Onclientclick
## ASP.NET Button OnClientClick Property
The `OnClientClick` property is a powerful attribute of the ASP.NET Web Server `Button` control. It allows developers to execute client-side JavaScript before the page posts back to the server.
---
## Definition and Usage
The `OnClientClick` property is used to specify a client-side script (typically JavaScript) that runs when a `Button` control is clicked.
### Key Features:
* **Client-Side Execution:** The script runs directly in the user's browser before any server-side code is triggered.
* **Postback Prevention:** You can use this property to validate user input or confirm actions. If the client-side script returns `false`, the server-side postback (`OnClick` event) is canceled.
* **Combined Execution:** When a button is clicked, the script defined in `OnClientClick` runs first. If it succeeds (or doesn't return `false`), the server-side event handler defined in `OnClick` is executed.
---
## Syntax
```asp
```
### Property Values
| Property | Description |
| :--- | :--- |
| **OnClientClick** | A string representing the client-side script (e.g., a JavaScript function call) to be executed when the button is clicked. |
---
## Code Example
The following example demonstrates how to use both `OnClientClick` (client-side) and `OnClick` (server-side) together.
In this scenario, when the user clicks the button, a JavaScript confirmation dialog box appears. If the user clicks **OK**, the script returns `true`, and the server-side event handler `script1` runs to display a message. If the user clicks **Cancel**, the script returns `false`, and the server-side postback is prevented.
```asp
<%@ Page Language="VB" %>
OnClientClick Demo
```
---
## Important Considerations
### 1. The Importance of the `return` Keyword
If you want to prevent the page from posting back to the server based on a condition (such as a failed validation or a canceled confirmation dialog), you **must** include the `return` keyword in the property declaration:
```asp
OnClientClick="return script2();"
```
If you only write `OnClientClick="script2();"`, the JavaScript function will execute, but the page will still post back to the server regardless of whether your function returns `true` or `false`.
### 2. Integration with ASP.NET Client-Side Validation
If your page uses ASP.NET Validator controls (like `RequiredFieldValidator`), ASP.NET automatically generates client-side validation code. If you override `OnClientClick`, make sure your custom script does not bypass these validators. You can manually trigger ASP.NET validation in your JavaScript using:
```javascript
if (Page_ClientValidate()) {
// Perform custom logic
return true;
}
return false;
```
YouTip