Bootstrap form validation not working after page PostBack in ASP.Net

Last Reply 3 months ago By dharmendr

Posted 3 months ago

I have a Gridview inside a Modal Popup. Selected Row value in the gridview assigned back to Asp.net form Textbox which is outside modal.

Everytime when i select gridview row i am experiencing page postback. so page flickers. how do i avoid this?

Its a Bootstrap validator.

steps to reproduce issue. click on search --> type 'a' and hit enter for search results in gridview.  select any row --> textbox losses validators

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Demo page</title>
 
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
        <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css" />
   <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css"/>
          <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
 
    <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
 
  <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js"></script>
</head>
<body>
 
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
 
    <script type="text/javascript">
        function openModal() {
            $('[id*=popModal]').modal({
                backdrop: 'static',
                keyboard: false
            });
            $('[id*=popModal]').on("hidden.bs.modal", function (e) {
                $('body').removeClass('modal-open');
                $('.modal-backdrop').remove();
            });
        }
    </script>
    <script type="text/javascript">
        function btnNameSearch_Click(objTextBox, objBtnID) {
            if (window.event.keyCode == 13) {
                document.getElementById(objBtnID).focus();
                document.getElementById(objBtnID).click();
            }
        }
 
</script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#myForm').bootstrapValidator({
                container: '#messages',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    'ctl00$ContentPlaceHolder1$txtResult': {
                        validators: {
                            notEmpty: {
                                message: '1st Textbox is required and cannot be empty'
                            }
                        }
                    },                 
                    'ctl00$ContentPlaceHolder1$txtOutside': {
                        validators: {
                            notEmpty: {
                                message: '2nd Textbox is required and cannot be empty'
                            }
                        }
                    },                  
                }
            });
        });
    </script>
</body>
</html>

 

public partial class _Default : System.Web.UI.Page
{
      
    protected void Page_Load(object sender, EventArgs e)
    {
 
        rblist.SelectedIndex = 2;
        this.txtEID.Attributes.Add("onkeypress", "btnNameSearch_Click(this,'" + this.btnNameSearch.ClientID + "')");
    }
    private void BindGrid()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("eid", typeof(int)),
                        new DataColumn("ename", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        gvEmployee.DataSource = dt;
        gvEmployee.DataBind();
        
    }
    protected void btnNameSearch_Click(object sender, EventArgs e)
    {
        clsBusinessLayer objBAL = new clsBusinessLayer();
        if (IsValid)
        {
            if (txtEID.Text == "" && txtEName.Text == "")
            {
                BindGrid();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "$(function() { openModal(); });", true);
            }
            else if (txtEID.Text == "" && txtEName.Text != "")
            {
                var dsEmployees = (DataSet)objBAL.LoadEmployees(txtEID.Text, txtEName.Text);
                gvEmployee.DataSource = dsEmployees.Tables[0];
                gvEmployee.DataBind();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "$(function() { openModal(); });", true);
            }
            else
            {
                //var dsEmployees = (DataSet)objBAL.LoadEmployees(txtEID.Text, txtEName.Text);
 
                BindGrid();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "$(function() { openModal(); });", true);
            }
 
        }
    }
 
 
 
    protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
            //e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
            //e.Row.ToolTip = "Click to Select row";
            e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.gvEmployee, "Select$" + e.Row.RowIndex);
        }
    }
 
    protected void gvEmployee_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow grow = gvEmployee.SelectedRow;
        if (grow != null)
        {
            txtResult.Text = grow.Cells[1].Text;
            txtResult.Focus();
        }
    }
}

 

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" EnableEventValidation="false" Inherits="_Default" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
     <form method="post" action="" id="myForm" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <div class="container">
          <br /><br /><br />
                <a href="#" data-target="#popModal" data-toggle="modal" class="btn btn-warning">Search Records</a><br /><br />
             <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                 <ContentTemplate>
                     <asp:TextBox ID="txtResult" runat="server"></asp:TextBox>
                 </ContentTemplate>
            </asp:UpdatePanel><br /><br />
            <asp:TextBox ID="txtOutside" runat="server"></asp:TextBox>
            <br /><br />
            <asp:RadioButtonList ID="rblist" runat="server">
                <asp:ListItem>Oral B</asp:ListItem>
                <asp:ListItem>Colgate</asp:ListItem>
                <asp:ListItem>Crest</asp:ListItem>
            </asp:RadioButtonList>
 
             <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                 <!-- Modal -->
                    <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
                    <div class="modal fade" id="popModal" tabindex="-1" role="dialog" style="overflow:hidden"  aria-labelledby="popModalLabel"
                        aria-hidden="true">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title" id="popModalLabel">
                                        Search Products</h4>
                                </div>
                                <div class="modal-body">
                                    <form id="inputform" action="#" method="post">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <asp:TextBox ID="txtEID" runat="server"  class="form-control"></asp:TextBox>
                                                </div>
                                            </div>
                             
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <asp:TextBox ID="txtEName" runat="server"  class="form-control"></asp:TextBox>
                                                </div>
                                            </div>
                                             
                                        </div>
  
  
                                    </form>
  
                                    <asp:Button ID="btnNameSearch" CssClass="btn btn-primary" Text="Search" UseSubmitBehavior="false" OnClick="btnNameSearch_Click" runat="server" />
                                </div>
                                <div class="modal-footer">
                                                                           
                                     <div style="width: 35%; height: 200px">
                                                  <asp:GridView ID="gvEmployee" runat="server" OnRowDataBound="gvEmployee_RowDataBound" DataKeyNames="eid" AutoGenerateColumns="false" CssClass="table table-hover" OnSelectedIndexChanged="gvEmployee_SelectedIndexChanged" GridLines="None">
                                                        <Columns>
                                                            <asp:BoundField DataField="eid" HeaderText="EID" />                                                            
                                                            <asp:BoundField DataField="ename" HeaderText="EName" /> 
                                                              
                                                        </Columns>
                                                         <HeaderStyle BackColor="LightCoral" ForeColor="White"></HeaderStyle>
                                  
                                             </asp:GridView>
                                        </div>
 
                                   <div class="dl-horizontal">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">
                                        Close</button>
  
                                  </div>
                                      
                                </div>
                            </div>
                        </div>
                    </div>
                    </ContentTemplate>
                   </asp:UpdatePanel>
            <div class="form-group">
        <div class="col-md-9 col-md-offset-3">
            <div id="messages"></div>
        </div>
    </div>
            <div class="form-group">
        <div class="col-md-1 col-md-offset-3">
            <button type="submit" class="btn btn-default">Validate</button>
        </div>
    </div>
             
         </div>
    </form>
</asp:Content>

 

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago

Check the code.

MagterPage

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css" />
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js"></script>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>
    <script type="text/javascript">
        function openModal() {
            $('[id*=popModal]').modal({
                backdrop: 'static',
                keyboard: false
            });
            $('[id*=popModal]').on("hidden.bs.modal", function (e) {
                $('body').removeClass('modal-open');
                $('.modal-backdrop').remove();
            });
        }
    </script>
    <script type="text/javascript">
        function btnNameSearch_Click(objTextBox, objBtnID) {
            if (window.event.keyCode == 13) {
                document.getElementById(objBtnID).focus();
                document.getElementById(objBtnID).click();
            }
        }
 
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            ValidateFormField();
        });
        function ValidateFormField() {
            $('[id*=myForm]').bootstrapValidator({
                container: '#messages',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    'ctl00$ContentPlaceHolder1$txtResult': {
                        validators: {
                            notEmpty: {
                                message: '1st Textbox is required and cannot be empty'
                            }
                        }
                    },
                    'ctl00$ContentPlaceHolder1$txtOutside': {
                        validators: {
                            notEmpty: {
                                message: '2nd Textbox is required and cannot be empty'
                            }
                        }
                    }
                }
            });
        }
    </script>
</body>
</html>

DefaultPage

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <form method="post" action="" id="myForm" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div class="container">
        <br />
        <br />
        <br />
        <a href="#" data-target="#popModal" data-toggle="modal" class="btn btn-warning">Search
            Records</a><br />
        <br />
        <asp:UpdatePanel ID="UpdatePanel2" runat="server">
            <ContentTemplate>
                <asp:TextBox ID="txtResult" runat="server"></asp:TextBox>
            </ContentTemplate>
        </asp:UpdatePanel>
        <br />
        <br />
        <asp:TextBox ID="txtOutside" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:RadioButtonList ID="rblist" runat="server">
            <asp:ListItem>Oral B</asp:ListItem>
            <asp:ListItem>Colgate</asp:ListItem>
            <asp:ListItem>Crest</asp:ListItem>
        </asp:RadioButtonList>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <!-- Modal -->
                <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
                <div class="modal fade" id="popModal" tabindex="-1" role="dialog" style="overflow: hidden"
                    aria-labelledby="popModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title" id="popModalLabel">
                                    Search Products</h4>
                            </div>
                            <div class="modal-body">
                                <form id="inputform" action="#" method="post">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <asp:TextBox ID="txtEID" runat="server" class="form-control"></asp:TextBox>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <asp:TextBox ID="txtEName" runat="server" class="form-control"></asp:TextBox>
                                        </div>
                                    </div>
                                </div>
                                </form>
                                <asp:Button ID="btnNameSearch" CssClass="btn btn-primary" Text="Search" UseSubmitBehavior="false"
                                    OnClick="btnNameSearch_Click" runat="server" />
                            </div>
                            <div class="modal-footer">
                                <div style="width: 35%; height: 200px">
                                    <asp:GridView ID="gvEmployee" runat="server" OnRowDataBound="gvEmployee_RowDataBound"
                                        DataKeyNames="eid" AutoGenerateColumns="false" CssClass="table table-hover" OnSelectedIndexChanged="gvEmployee_SelectedIndexChanged"
                                        GridLines="None">
                                        <Columns>
                                            <asp:BoundField DataField="eid" HeaderText="EID" />
                                            <asp:BoundField DataField="ename" HeaderText="EName" />
                                        </Columns>
                                        <HeaderStyle BackColor="LightCoral" ForeColor="White"></HeaderStyle>
                                    </asp:GridView>
                                </div>
                                <div class="dl-horizontal">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">
                                        Close</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
        <div class="form-group">
            <div class="col-md-9 col-md-offset-3">
                <div id="messages">
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-1 col-md-offset-3">
                <button type="submit" class="btn btn-default">
                    Validate</button>
            </div>
        </div>
    </div>
    </form>
</asp:Content>

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    rblist.SelectedIndex = 2;
    this.txtEID.Attributes.Add("onkeypress", "btnNameSearch_Click(this,'" + this.btnNameSearch.ClientID + "')");
}
private void BindGrid()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("eid", typeof(int)),
                    new DataColumn("ename", typeof(string)),
                    new DataColumn("Country",typeof(string)) });
    dt.Rows.Add(1, "John Hammond", "United States");
    dt.Rows.Add(2, "Mudassar Khan", "India");
    dt.Rows.Add(3, "Suzanne Mathews", "France");
    dt.Rows.Add(4, "Robert Schidner", "Russia");
    gvEmployee.DataSource = dt;
    gvEmployee.DataBind();

}
protected void btnNameSearch_Click(object sender, EventArgs e)
{
    //clsBusinessLayer objBAL = new clsBusinessLayer();
    if (IsValid)
    {
        if (txtEID.Text == "" && txtEName.Text == "")
        {
            BindGrid();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "$(function() { openModal(); });", true);
        }
        else if (txtEID.Text == "" && txtEName.Text != "")
        {
            //var dsEmployees = (DataSet)objBAL.LoadEmployees(txtEID.Text, txtEName.Text);
            //gvEmployee.DataSource = dsEmployees.Tables[0];
            //gvEmployee.DataBind();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "$(function() { openModal(); });", true);
        }
        else
        {
            //var dsEmployees = (DataSet)objBAL.LoadEmployees(txtEID.Text, txtEName.Text);

            BindGrid();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "$(function() { openModal(); });", true);
        }

    }
}



protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
        //e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
        //e.Row.ToolTip = "Click to Select row";
        e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.gvEmployee, "Select$" + e.Row.RowIndex);
    }
}

protected void gvEmployee_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow grow = gvEmployee.SelectedRow;
    if (grow != null)
    {
        txtResult.Text = grow.Cells[1].Text;
        txtResult.Focus();
    }
}

Screenshot