Pages

Mar 2, 2010

how to make the server side button click event firing depend on javascript return?

Using OnClick and OnClientClick:
Usually we have situations where we have to check for something in the client side and decide whether to fire the server side event or not.
Say for eg.
some client side validations. Lets see how to do this
Now in the sever side OnClick event i have certain operation to be performed, 
before that i need to make some client side validations. 
Say for eg. To check for GridView's count and decide whether to allow or stop the servide side event firing.

<asp:Button ID="btnSubmit" runat="server" 

OnClientClick="javascript:return CheckGridCount();" OnClick="btnSubmit_Click" />
Above is the way we call the javascript method CheckGridCount() to perform the check.



function CheckGridCount()
{
    var gv = document.getElementById('gridView1');
    var count = gv.rows.length;
    if(count >0)
  {
     return true;
  }
  else
  {
   alert("Please select Atleast one item");
    return false;
  }
}

If the above method return true then the server side event fires and postback occurs
else an alert is shown and nothing happens thus avoiding an unnecessary postback.