views:

72

answers:

2

If I use both onclick() and onClientClick() can I make sure that server side will be called only after client side function returns TRUE or vice versa?

For example:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Import Namespace="System.Xml" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

 <%
 protected void save_n_display(object sender, EventArgs e)
 {
    // This must be called when validate() returns true...
 }
 %>

<asp:Button ID="Button1"  OnClientClick="validate()" onClick="save_n _display" "Text="Check" runat="server" />


<script type="text/javascript" language="javascript">
    function validate()    // client side Validation is done
    {

    }
</script>

So can I use onclick() and onClientClick() or do I need something different for this? I even tried passing variables from javascript to asp functions so when validate returns true then save_n _display will be called.

A: 

However you get your client side click event registered it doesn't matter. Though if you are using a server control then you do want to use onclientclick. But the key is that you want to use return Validate(). Then in your validate method you return a true or false value depending on whether it validated or not.

EDIT: So make onclientclick look like this:

onclientclick="return Validate();"

Then in the validate function:

function Validate()
{
    return true;
}
spinon
so if validate returns false...onClick ownt be called or wat??
Sangram Nandkhile
@Sangram that's correct, if Validate() returns false, the click event will be cancelled
Jiaaro
A: 

I have to go find the example...but I just did the on-click event. In the codebehind, I ran my ServerSide code...or I would register a script on the page to call the JS validation and then run the codebehind code.

Learn about RegisterStartupScript

OnClick="MyCodeBehindMethod()"

Then, in the codebehind have:

    //Verify and validate conditions
    string script1="<script language=JavaScript>"
    script1 += "Validate();"
    script1 += "</script>"
    Page.RegisterStartupScript("clientscript",script1);
The Mirage