Why does a button event function run during a page reload in ASP.NET?

烂漫一生 提交于 2020-01-24 21:41:06

问题


public partial class Stats : System.Web.UI.Page
{
    public SqlDataReader DataReader;
    public SqlCommand Command;
    string queryString = ("INSERT INTO UserData (UserProfileID, ConfidenceLevel, LoveLevel, HappinessLevel) VALUES ('a051fc1b-4f51-485b-a07d-0f378528974e', 1, 1, 1);");

    protected void Page_Load(object sender, EventArgs e)
    {
       LabelUserID.Text = Membership.GetUser().ProviderUserKey.ToString();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        MySqlConnection database = new MySqlConnection();
        database.CreateConn();

        Command = new SqlCommand(queryString, database.Connection);
        Command.ExecuteNonQuery();        
    }
}

Not sure I understand why Button1_Click() is executing on a page reload.

I put in a break point in the function and it does hit it as well as update the DataBase.


回答1:


If you click the button to post back, then reload after the postback, you're essentially repeating the postback, which will cause the button event to execute again. This will not happen if you simply reload the page after a GET request.




回答2:


What do you mean a page reload? If you clicked the button, then hit refresh on the browser, that will cause the browser to re-issue the last post, which means as far as the server is concerned, the button is being clicked again. (The browser should warn you about re-posting though.)

If it's occurring the first time you request the page then perhaps you accidentally wired up the wrong event handler in the ASPX file?

When in doubt, fire up Fiddler to see what's being transmitted to the server.



来源:https://stackoverflow.com/questions/3182932/why-does-a-button-event-function-run-during-a-page-reload-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!