开发者

How to prevent PostBack on the client side?

I have some validation JS code on client, tha开发者_开发技巧t must be executed befor PostBack. If this validation code return 'false', postback is needless. How it can be disabled?


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.


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/


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();">


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜