Stremlenye
Stremlenye

Reputation: 595

How to prevent PostBack on the client side?

I have some validation JS code on client, that must be executed befor PostBack. If this validation code return 'false', postback is needless. How it can be disabled?

Upvotes: 3

Views: 16976

Answers (5)

user132936
user132936

Reputation: 104

If the postback is being triggered by a button then you can do something like this:

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return IsValid();" />

If the IsValid function returns false then the postback will be prevented. If you want to catch all postbacks regardless of which control triggers it then you can use
<form id="form1" runat="server" onsubmit="return IsValid();">

Upvotes: 2

Joel Coehoorn
Joel Coehoorn

Reputation: 416149

Remember that the real validation should always happen on the server. Anything you do client-side is merely an optimization to save a few http round trips.

The easiest way to keep your client side and server-side validation in sync with ASP.Net is to use the validation controls. The validation controls will do both client side and server side validation, in such a way that if validation fails on the client it never posts to the server.

If you want to do something that's not covered by the standard validation controls, you should either use a CustomValidator or inherit your own control from BaseValidator.

Upvotes: 4

AaronSieb
AaronSieb

Reputation: 8266

Depending on the validation you're attempting, you may also be able to use the CustomValidator control. This would also allow you to easily implement your validation logic on the server side.

Upvotes: 0

Kate
Kate

Reputation: 775

What do you use: some validator or some button with onclick event? If you have

<input type="button" id="btnID" runat="server" onclick="CheckValid();"/>

function CheckValid()
{
   if(!IsValid) return false;//then no post back occer
}

Upvotes: 0

Ed B
Ed B

Reputation: 6054

Set the OnClientClick='YourJSValidationFunction' on your ASP button.

Then have the YourJSValidationFunction return true or false.

False will prevent postback

Example: http://vijaymodi.wordpress.com/2007/06/08/button-onclick-and-onclientclick-2/

Upvotes: 3

Related Questions