J.C
J.C

Reputation: 752

How to stop page from reloading when asp button is pressed?

I have created form with many fields that on page load loads information about a specific user. When the user click on the button update the page seems to be reloading and then sends the sames informations to the server.

I have looked at similaire answers on stackoverflow but none seem to work for me.

Here is my front end.

<asp:TextBox ID="BirthDate" type="text" runat="server" class="form-control" 
 placeholder="fecha nacimiento"  aria-describedby="inputGroupPrepend" 
 required="required"></asp:TextBox>

<asp:Button class="btn btn-primary" ID="update" runat="server" Text="actualizar"  AutoPostback="false" OnClick="update_Click"/>

and here is my back end.

    //This is where the textboxes are populated 
    protected void Page_Load(object sender, EventArgs e)
    {
        string employeID = gestiondeempleados.empleadoID;

        string queryStr = "SELECT empleado_id,nombreusuario,nombre  Where empleado_id =" + employeID;
        using (conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
        {
            using (cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn))
            {
                conn.Open();
                using (reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                         firstname.Text = reader.GetString(reader.GetOrdinal("nombre"));
                    }
                }
            }
        }


    //This is where the change textbox should be send to the database

    protected void update_Click(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string UpdateStatement1;


            UpdateStatement1 = "update erp_empleados set " +
            "nombre = '" + firstname.Text "' where empleado_id = " + 
             gestiondeempleados.empleadoID;

            debugmsg.Text = UpdateStatement1;

            //MySql connection code....

        }

    }

I want the changed text field to be send and not same text field I have loaded initial.

Upvotes: 0

Views: 115

Answers (2)

Mohammad Ghanem
Mohammad Ghanem

Reputation: 726

I suggest to use Ajax request instead of asp.net web forms events, this is the standard and modern approach to submit data without postback in any web applications framework.

You need to create a web method and call it , you can search more "asp.net web method ajax jquery calling"

$('#btnSave').click(function (e) {
    e.preventDefault(); //
    var element = this;    
    $.ajax({
        url: "YOUR_WEB_METHOD_URL",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert("Done");
                $(element).closest("form").submit(); //<------------ submit form
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

Or you can use update panel (Very easy approach and you will use same asp.net events but I'm not recommended this approach because its inject a lot of not clear scripts to your page and its not the best practice from security side and maybe partially not working with some modern versions of browsers).

To use update panel please take look on below link

https://www.c-sharpcorner.com/UploadFile/f50501/use-updatepanel-control-in-Asp-Net/

Upvotes: 1

J.C
J.C

Reputation: 752

I figured it out.All I hate to do was adding !IsPostBack were the variable where initialized. I am not sure why doe could anyone clarify the reason.

//This is where the textboxes are populated 
protected void Page_Load(object sender, EventArgs e)
{

   if (!IsPostBack)
   {
    string employeID = gestiondeempleados.empleadoID;

    string queryStr = "SELECT empleado_id,nombreusuario,nombre  Where empleado_id =" + employeID;

    using (conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
    {
        using (cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn))
        {
            conn.Open();
            using (reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                     firstname.Text = reader.GetString(reader.GetOrdinal("nombre"));
                }
            }
        }
    }
}

Upvotes: 0

Related Questions