YouTip LogoYouTip

Prop Webcontrol Linkbutton Onclientclick

# ASP.NET LinkButton OnClientClick Property The `OnClientClick` property of the ASP.NET `LinkButton` control allows developers to specify a client-side script (typically JavaScript) that executes when the control is clicked. This property is highly useful for performing client-side validation, displaying confirmation dialogs, or triggering UI animations before the page posts back to the server. --- ## Definition and Usage The `OnClientClick` property sets or returns the client-side script that runs when the `LinkButton` control is clicked. In ASP.NET, a `LinkButton` normally triggers a postback to execute server-side code defined in its `OnClick` event. By using `OnClientClick`, you can run JavaScript on the user's browser *before* that postback occurs. ### Key Behavior: * **Pre-processing:** The client-side script runs first. * **Canceling Postback:** If the client-side script returns `false`, the server-side `OnClick` event is canceled, preventing the page from posting back to the server. * **Continuing Postback:** If the client-side script returns `true` (or does not return a value), the page posts back and executes the server-side event handler. --- ## Syntax ```asp ``` ### Property Values | Property Value | Description | | :--- | :--- | | `string` | The client-side script (such as a JavaScript function call) to be executed when the `LinkButton` is clicked. | --- ## Code Example The following example demonstrates how to use both `OnClientClick` (client-side JavaScript) and `OnClick` (server-side VB.NET code) together. When the user clicks the link button, a JavaScript confirmation box appears. If the user clicks "OK", the page posts back and runs the server-side script to display a greeting. If the user clicks "Cancel", the postback is aborted. ```asp <%@ Page Language="VB" %> LinkButton OnClientClick Example


``` --- ## Important Considerations ### 1. The `return` Keyword When using `OnClientClick` to prevent a postback, you must include the `return` keyword in the property declaration: ```asp OnClientClick="return confirmAction();" ``` If you omit `return` (e.g., `OnClientClick="confirmAction();"`), the page will still post back to the server regardless of whether your JavaScript function returns `false`. ### 2. Client-Side Validation Integration `OnClientClick` is commonly used alongside ASP.NET validation controls. If you want to manually trigger page validation before running custom JavaScript, you can use the built-in ASP.NET client-side API: ```asp OnClientClick="if (typeof(Page_ClientValidate) == 'function') { if (Page_ClientValidate() == false) { return false; } } return confirm('Do you want to submit?');" ```
← Prop Webcontrol Linkbutton PosProp Webcontrol Imagebutton Va β†’