How to insert data typed on a TextBox from modal into database

I have a JavaScript modal that opens on a button click and has two text boxes and a button. The button has the task to insert the data that has been typed into the text boxes to a database. But, I don’t know why, when I click the button it just refreshes my page and the data is not inserted into the database. I also wrapped two alerts in a try/catch block, thus the one appears if the operation is successful and the other one if not, but for some reason after clicking the button none of them appears (the alert after an unsuccessful operation needs to pop up). I’ve searched the whole Internet but I don’t know why for my certain case I can’t find a thing (most of the solutions were for PHP).

How to make the button that is on the modal functional and to collect the data from the text boxes and insert to the database?

Here is the HTML code of the modal:

<i class="fas fa-info-circle" id="info"></i>
<div class="popup" id="popup">
  <div class="modal-container" id="modal_container">
    <div class="popup_left">
      <div class="popup-img_container">
        <img
          src="img/database_system.jpg"
          alt="Database System"
          class="popup_img"
        />
      </div>
    </div>
    <div class="popup_right">
      <div class="right_content">
        <h1>Can't reach me online?</h1>
        <p>
          Please type your e-mail and provide a brief explanation of your
          intention/purpose of contacting.
        </p>
        <form method="post" enctype="multipart/form-data">
          <asp:TextBox
            ID="email_textbox"
            CssClass="popup_form"
            placeholder="Please enter your e-mail"
            runat="server"
            Required="required"
          ></asp:TextBox>
          <asp:RegularExpressionValidator
            ID="validator1"
            runat="server"
            ErrorMessage="Invalid character, your e-mail address must contain @"
            ControlToValidate="email_textbox"
            ValidationExpression="w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*"
          ></asp:RegularExpressionValidator>
          <asp:TextBox
            ID="email_message"
            CssClass="popup_form"
            placeholder="Message"
            runat="server"
            Required="required"
          ></asp:TextBox>
          <asp:Button
            ID="Message_button"
            runat="server"
            Text="Send"
            type="button"
            OnClick="Message_button_Click"
          />
        </form>
      </div>
    </div>
    <button id="close" type="button">
      <div class="popup_close">
        <svg>
          <use xlink:href="img/sprite.svg#icon-cross"></use>
        </svg>
      </div>
    </button>
  </div>
</div>

Here is the C# code:

SqlConnection con = new SqlConnection(@"Data Source=;Initial Catalog=Contacts;Persist Security Info=True;User ID=;Password=");
    protected void Message_button_Click(object sender, EventArgs e)
    {
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.CommandText = "INSERT INTO ContactsTable VALUES ('"+email_textbox.Text+"','"+email_message.Text+"')";
        cmd.ExecuteNonQuery();

        try
        {
            script += successMessage;
            script += "')};";
            ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
        }
        catch (Exception)
        {

            script += dbFailMessage;
            script += "')};";
            ClientScript.RegisterStartupScript(this.GetType(), "dbFailMessage", script, true);
        }
        email_textbox.Text = "";
        email_message.Text = "";
    }

Here is the JavaScript code:

const info = document.getElementById('info');
const popup = document.getElementById('popup');
const close = document.getElementById('close');

info.addEventListener('click', () => {
   popup.classList.add('show');
});

close.addEventListener('click', () => {
   popup.classList.remove('show');
});

Grateful for any help.

Answer

ok, there are some issues here.

first up, it not quite clear what JavaScirpt libaries you are using to pop up that dialog – there are a LOT of them. It kind of looks like bootstrap, but there must be more the.

But, lets keep this nice and simple. I’ll use jQuery.UI (since 99% of sites already have jQuery, adding the jQuery.UI library seems reaonsable).

So, how will this work?

Ok, we will pop the dialog. If the user hits cancel, then we just dismmiss (close) the dialog. if user hits add, then our plain jane button (in that pop dialog) will then do a post back and run code behind like any other simple button.

Because that plain jane button does a post back, then of couse the dialog will collapse and be dismissed for us.

So, say we have this markup:

        <asp:Button ID="cmdAddHotel" runat="server" Text="Add a Hotel" OnClientClick="popaddhotel();return false"/>

        <div id="AddHotelPop" style="text-align:right;display:none">

            <p>Hotel Name:<asp:TextBox ID="txtHotel" runat="server"></asp:TextBox></p>
            <p>First Name:<asp:TextBox ID="txtFirst" runat="server"></asp:TextBox></p>
            <p>Last Name:<asp:TextBox ID="txtLast" runat="server"></asp:TextBox></p>
            <p>City:<asp:TextBox ID="txtCity" runat="server"></asp:TextBox></p>
            <p>Province:<asp:TextBox ID="txtProvince" runat="server"></asp:TextBox></p>
            <p>Is Active:<asp:CheckBox ID="chkActive" runat="server"></asp:CheckBox></p>

            <p>
                <asp:Button ID="cmdAddOk" runat="server" Text="Ok-add" OnClick="cmdAddOk_Click" />
                <asp:Button ID="cmdCancel" runat="server" Text="Cancel" Style="margin-left:25px"
                    OnClientClick="MyClose();return false"/>
            </p>
        </div>

        <script>

            function popaddhotel() {
                var mydiv = $("#AddHotelPop")
                mydiv.dialog({
                    modal: true, appendTo: "form",
                    title: "Add Hotel", closeText: "",
                    width: "400px"
                });

            }

            function MyClose() {
                popdiv = $('#AddHotelPop')
                popdiv.dialog('close')
            }

        </script>

ok, we now get this:

enter image description here

And our simple button code behind to add to the database is this:

    protected void cmdAddOk_Click(object sender, EventArgs e)
    {
        using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblHotels WHERE ID = 0",
            new SqlConnection(Properties.Settings.Default.TEST3)))
        {
            cmdSQL.Connection.Open();
            DataTable rst = new DataTable();
            rst.Load(cmdSQL.ExecuteReader());
            SqlDataAdapter dUpdate = new SqlDataAdapter(cmdSQL);
            SqlCommandBuilder sUpdate = new SqlCommandBuilder(dUpdate);
            DataRow OneRow = rst.NewRow();

            OneRow["FirstName"] = txtFirst.Text;
            OneRow["LastName"] = txtLast.Text;
            OneRow["HotelName"] = txtHotel.Text;
            OneRow["City"] = txtCity.Text;
            OneRow["Province"] = txtProvince.Text;
            OneRow["Active"] = chkActive.Checked;
            rst.Rows.Add(OneRow);
            dUpdate.Update(rst);

        }
    }
}

so above is quite simple – clean, and we can follow the button clicks etc.

The above of course used jquery.ui for this (so you have to add that).

Edit: the question was asked which js libraries am I using.

Well, out of the box, all asp.net sites based on default templates have jQuery, so only jQuery.UI need be added.

But, to keep this all in one – for this post?

I included jquery. jqquery.UI, and the nice theme for jQuery.UI.

You will note that we don’t even need bootstrap libraries for this.

Sure, this works:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>