locked
Close the Jquery popup from code behind using data-dismiss attributes RRS feed

  • Question

  • User1587720337 posted

    We have a jquery popup with close and Add button, the close button is working tine with data-dismiss attribute, now i want to call the same attributes in code behind  on btnAdd event, here is the code

    <asp:Button ID="btnClose" data-dismiss="modal" runat="server" Text="close" CssClass="btn btn-default" Width="80px" Height="40px" />

    <asp:Button ID="btnAdd" OnClick="btnAdd_Click" runat="server" Text="attach" CssClass="btn btn-primary" Width="80px" Height="40px" />

    protected void btnAdd_Click(object sender, EventArgs e)
    {

    //need to call the  data-dismiss="modal"

    }

    Any ideas how to do that?

    Tuesday, February 11, 2020 5:14 AM

Answers

  • User665608656 posted

    Hi Srishti ,

    According to your needs, I suggest that you can write the content that needs to be partially refreshed on another page, and then call it through the iframe.

    When you click the add button, the webmethod will be executed, and then only the iframe module will be refreshed in the success method.

    You can ensure that the values of other controls exist, and you can also ensure that the module you need to change is refreshed.

    A case is made below for your reference:

    WebForm16.aspx :

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    
        <script> 
            function myFunction() { 
                var arrImage = $("#TextBox2").val().split(',');
                $.ajax({
                    type: "POST",
                    url: "WebForm16.aspx/AddImage",
                    //data: "{'arrImage':'" + arrImage + "'}",
                    data: JSON.stringify({ arr: arrImage }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var str = data.d;
                        //alert(str);
                        if (str.indexOf('successfully') > -1) {
                            var iframe = document.getElementById('unit');
                            iframe.src = iframe.src;
                        }
                        else {
                            alert('Oops!!!');
                            //  window.open('?', '_self');
                        }
                    },
                    error: function (msg) {
                        alert('failed');
                    }
                });
                //  return false;
            }
        </script>
    </head>
    <body>
        <form runat="server">
            <div class="container">
                Other Control:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
                <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
                <div class="modal fade" id="myModal" role="dialog">
                    <div class="modal-dialog">
                        <!-- Modal content-->
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                <h4 class="modal-title">Modal Header</h4>
                            </div>
                            <div class="modal-body">
                                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                            </div>
                            <div class="modal-footer">
                                <asp:Button ID="btnClose" data-dismiss="modal" runat="server" Text="close" CssClass="btn btn-default" Width="80px" Height="40px" />
                                <%--  <input type="button" id="btnAdd1" runat="server" onserverclick="btnAdd1_ServerClick" value="attach" class="btn btn-primary" style="width: 80px !important; height: 40px !important;" />--%>
                                <input type="button" id="btnAdd1" onclick="myFunction();" value="attach" class="btn btn-primary" style="width: 80px !important; height: 40px !important;" data-dismiss="modal" />
                            </div>
                        </div>
    
                    </div>
                </div>
                <div>
                    <iframe id="unit" name="unit" src="partview.aspx" style="width: 500px; height: 300px; border: 0px;"></iframe>
                </div>
    
    
            </div>
    
        </form>
    
    </body>
    </html>
    [WebMethod]
            public static string AddImage(List<string> arr)
            {
                string strResult = string.Empty;
                string strImageURL = string.Empty;
                if (Convert.ToString(HttpContext.Current.Session["ImageURL"]) != "0")
                {
                    strImageURL = Convert.ToString(HttpContext.Current.Session["ImageURL"]);
                }
                for (int i = 0; i < arr.Count; i++)
                {
                    strImageURL += arr[i].ToString() + ",";
                }
    
                string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString.ToString();
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("insert into Schools (school_name) values (@school_name)"))
                    {
                        cmd.Parameters.AddWithValue("@school_name", strImageURL);
                        cmd.Connection = con;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
                HttpContext.Current.Session["ImageURL"] = strImageURL;
                strResult = "successfully";
                return strResult;
            }
    

    partview.aspx:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                    <asp:GridView ID="GridView1" runat="server"></asp:GridView>
            </div>
        </form>
    </body>
    </html>
    

    partview.aspx.cs:

            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                { 
                    BindData();
                }
            }
            public void BindData()
            {
                string query = "SELECT * FROM Schools";
                SqlCommand cmd = new SqlCommand(query);
                string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString.ToString();
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataSet ds = new DataSet())
                        {
                            sda.Fill(ds);
                            GridView1.DataSource = ds.Tables[0];
                            GridView1.DataBind();
                        }
                    }
                }
            }

    Here is the result of this demo:

    If this still doesn't solve your problem, I suggest you provide us with detailed code.

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 12, 2020 9:41 AM

All replies

  • User665608656 posted

    Hi Srishti ,

    We have a jquery popup with close and Add button, the close button is working tine with data-dismiss attribute, now i want to call the same attributes in code behind  on btnAdd event, here is the code

    To add attribute to the control in the code behind, you can refer to the following code:

        protected void btnAdd_Click(object sender, EventArgs e)
            {
                btnAdd.Attributes["data-dismiss"] = "modal";
            }
    

    As far as I know, the use of data-dismiss in bootstrap is to close the modal popup box without refreshing the page.

    When you trigger the onclick code behind event of the add button and add the data-dismiss property to the button, the page will refresh immediately , the attribute will also disappear, so if you add the attribute in the onclick code behind event will not prevent you from clicking the add button to refresh the page.

    If you just want to click the add button and the page will not refresh, then I suggest you use ajax with webmethod to achieve your needs.

    If I understand correctly, I suggest you provide us with your detailed requirements and code, if not, then please tell us your detailed requirements.

    Best Regards,

    YongQing.

    Tuesday, February 11, 2020 8:25 AM
  • User1587720337 posted

    Adding the below code is not working and i think you are right;

     btnAdd.Attributes["data-dismiss"] = "modal";

    Challenge with Ajax with Web method:

    On child popup I have datalist control with checkbox by which user can select the images by checking the checkbox, now how we can pass the control or selected checkbox values to web method.

    Below is the code that I have tried earlier which is not working

    [WebMethod]
    public static string AddTImage( string strSelectedID, System.Web.UI.WebControls.DataList DataList1)
    {

    for (int i = 0; i < DataList1.Items.Count; i++)
    {

    CheckBox chkSelect = DataList1.Items[i].FindControl("chkSelect") as CheckBox;

    string strSizeType = string.Empty;
    if (chkSelect != null)
    {
    if (chkSelect.Checked)
    {
    strID += fn.Value + ",";

    }

    ]

    return strResult;
    }

    aspx page

    <script>
    function myFunction() {

    var strSelectedID = document.getElementById('<%=chkSelect.ClientID%>').value;
    var DataList1 = document.getElementById('<%=datalist1.ClientID%>').value;
    $.ajax({
    type: "POST",
    url: "AddKeywordImageDialog.aspx/AddKeywordImage",
    data: "{'strSelectedID':'" + strSelectedID + "','DataList1':'" + DataList1 + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
    var str = data.d;

    if (str.indexOf('successfully') > -1) {

    }
    else {

    //window.open('?', '_self');
    }
    },
    error: function (msg) {
    alert('failed');
    }
    });
    }
    }

    </script>

    is it possible to pass the control like datalist to web method?

    Tuesday, February 11, 2020 8:44 AM
  • User1587720337 posted

    I am able to get this done using ajax with web method, now the problem I have when I closed the popup by clicking on add button event, the parent page get refreshed and all the values on the parent page disappeared, any idea what's causing this. here is the complete code, 

    cs pages

    public static string AddImage(List<string> arr)

        {

            string strResult = string.Empty;

            string strImageURL = string.Empty;

            if (Convert.ToString(HttpContext.Current.Session["ImageURL"]) != "0")

            {

                strImageURL = Convert.ToString(HttpContext.Current.Session["ImageURL"]);

            }

            for (int i = 0; i < arr.Count; i++)

            {

                strImageURL += arr[i].ToString() + ",";

            }

            HttpContext.Current.Session["ImageURL"] = strImageURL;

            strResult = "successfully";

            return strResult;

        }

    aspx.cs code:

    <script>

            function myFunction() {

                var dl = document.getElementById("<%=DataList1.ClientID%>");

                var items = dl.getElementsByTagName("input");

                var selectedItems = "";

                var arrImage = new Array();

                var selectedItemsID = 0;

                for (var i = 0; i < items.length; i++) {

                    if (items[i].type == 'checkbox' && items[i].checked == true) {

                        selectedItemsID = items[i].id.substring(20, 30);

                        var imgProfile = document.getElementById('DataList1_hdURL_' + selectedItemsID+'');

                        selectedItems += imgProfile.value + "\n"; 

                        arrImage.push(imgProfile.value);

                    }

                }

                $.ajax({

                    type: "POST",

                    url: "ImageDialog.aspx/AddImage",

                    //data: "{'arrImage':'" + arrImage + "'}",

                    data: JSON.stringify({ arr: arrImage }),

                    contentType: "application/json; charset=utf-8",

                    dataType: "json",

                    success: function (data) {

                        var str = data.d;

                        //alert(str);

                        if (str.indexOf('successfully') > -1) {

                            window.open('?', '_self');

                        }

                        else {

                            alert('Oops!!!');

                             window.open('?', '_self');

                        }

                    },

                    error: function (msg) {

                        alert('failed');

                    }

                });  

            }

        </script>

    <input type="button" id="btnAdd1" onclick="myFunction();" value="attach" class="btn btn-primary" style="width: 80px !important; height: 40px !important;"  data-dismiss="modal"  />

    Tuesday, February 11, 2020 12:15 PM
  • User665608656 posted

    Hi Srishti ,

    Based on the information you provided, I can't test it completely, because you didn't provide the full code for our reference.

    I found that the reason the page still refreshes when you click the add button is that in the success method in ajax, you executed "window.open('?', '_self');" after the data was returned.

    This sentence caused the page to refresh, instead of the page refresh caused by the add button you clicked.

    If you delete "window.open('?', '_self');" the page will not refresh.

    I suggest that you describe your requirements in detail and provide complete code, which will help us solve your problems more easily.

    Best Regards,

    YongQing.

    Wednesday, February 12, 2020 2:28 AM
  • User1587720337 posted

    Everything seems to be working, the only challenge is after closing the popup it refreshes the page as expected, but it also loses the values of the other controls on parent window.  I want to refresh the page and keep the old values in parent window the same.

    Wednesday, February 12, 2020 2:40 AM
  • User665608656 posted

    Hi Srishti ,

    According to your needs, I suggest that you can write the content that needs to be partially refreshed on another page, and then call it through the iframe.

    When you click the add button, the webmethod will be executed, and then only the iframe module will be refreshed in the success method.

    You can ensure that the values of other controls exist, and you can also ensure that the module you need to change is refreshed.

    A case is made below for your reference:

    WebForm16.aspx :

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    
        <script> 
            function myFunction() { 
                var arrImage = $("#TextBox2").val().split(',');
                $.ajax({
                    type: "POST",
                    url: "WebForm16.aspx/AddImage",
                    //data: "{'arrImage':'" + arrImage + "'}",
                    data: JSON.stringify({ arr: arrImage }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var str = data.d;
                        //alert(str);
                        if (str.indexOf('successfully') > -1) {
                            var iframe = document.getElementById('unit');
                            iframe.src = iframe.src;
                        }
                        else {
                            alert('Oops!!!');
                            //  window.open('?', '_self');
                        }
                    },
                    error: function (msg) {
                        alert('failed');
                    }
                });
                //  return false;
            }
        </script>
    </head>
    <body>
        <form runat="server">
            <div class="container">
                Other Control:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
                <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
                <div class="modal fade" id="myModal" role="dialog">
                    <div class="modal-dialog">
                        <!-- Modal content-->
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                <h4 class="modal-title">Modal Header</h4>
                            </div>
                            <div class="modal-body">
                                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                            </div>
                            <div class="modal-footer">
                                <asp:Button ID="btnClose" data-dismiss="modal" runat="server" Text="close" CssClass="btn btn-default" Width="80px" Height="40px" />
                                <%--  <input type="button" id="btnAdd1" runat="server" onserverclick="btnAdd1_ServerClick" value="attach" class="btn btn-primary" style="width: 80px !important; height: 40px !important;" />--%>
                                <input type="button" id="btnAdd1" onclick="myFunction();" value="attach" class="btn btn-primary" style="width: 80px !important; height: 40px !important;" data-dismiss="modal" />
                            </div>
                        </div>
    
                    </div>
                </div>
                <div>
                    <iframe id="unit" name="unit" src="partview.aspx" style="width: 500px; height: 300px; border: 0px;"></iframe>
                </div>
    
    
            </div>
    
        </form>
    
    </body>
    </html>
    [WebMethod]
            public static string AddImage(List<string> arr)
            {
                string strResult = string.Empty;
                string strImageURL = string.Empty;
                if (Convert.ToString(HttpContext.Current.Session["ImageURL"]) != "0")
                {
                    strImageURL = Convert.ToString(HttpContext.Current.Session["ImageURL"]);
                }
                for (int i = 0; i < arr.Count; i++)
                {
                    strImageURL += arr[i].ToString() + ",";
                }
    
                string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString.ToString();
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("insert into Schools (school_name) values (@school_name)"))
                    {
                        cmd.Parameters.AddWithValue("@school_name", strImageURL);
                        cmd.Connection = con;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
                HttpContext.Current.Session["ImageURL"] = strImageURL;
                strResult = "successfully";
                return strResult;
            }
    

    partview.aspx:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                    <asp:GridView ID="GridView1" runat="server"></asp:GridView>
            </div>
        </form>
    </body>
    </html>
    

    partview.aspx.cs:

            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                { 
                    BindData();
                }
            }
            public void BindData()
            {
                string query = "SELECT * FROM Schools";
                SqlCommand cmd = new SqlCommand(query);
                string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString.ToString();
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataSet ds = new DataSet())
                        {
                            sda.Fill(ds);
                            GridView1.DataSource = ds.Tables[0];
                            GridView1.DataBind();
                        }
                    }
                }
            }

    Here is the result of this demo:

    If this still doesn't solve your problem, I suggest you provide us with detailed code.

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 12, 2020 9:41 AM