Sunday, October 20, 2013

How to Prevent Page Postback if Validation is false using Jquery in ASP.Net

Leave a Comment
Let us check in this tutorial how to prevent server side code from executing  if the validation is false using jquery in asp.net.
Some time you want to prevent the code from running if user haven't filled certain required fields.
In this example I am using simple asp.net text box control and if user haven't filled the text box then the button click event won't execute on the server side.

Sample code :
Explanation: The Button1 Click event won't be fired until user doesn't enter some text in the text box. So in this way you can prevent server code from executing until validation are not satisfied using jquery.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {


            $('#Button1').click(function () {

                var uname = $('#txtname').val();
                if (uname == '') {
                    alert("Please Enter Name");
                    return false;
                }
                else
                {
                    return true;
                }

            });
        });


    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox runat="server" ID="txtname"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
          
        </div>
    </form>
</body>

</html>

Code Behind Button Click Event:
 protected void Button1_Click(object sender, EventArgs e)
    {

    }

0 comments:

Post a Comment