按下F5时如何防止重复插入

本文关键字:插入 何防止 F5 按下 | 更新日期: 2023-09-27 18:20:17

在下面的代码中,iam正在执行在db中插入值的功能。一切都很好,但问题是,如果我按F5或Ctrl+F5,页面将被重新加载,并且相同的值将再次插入。我刚刚清空了文本框的值,但它不起作用。如何防止重复插入。。

提前感谢。

 protected void btnAddNewQuestion_Click(object sender, EventArgs e)
        {
            try
            {
                SqlCommand cmd = new SqlCommand("Usp_insertNewQuestion", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@AppID", SqlDbType.Int).Value = applicationId;
                cmd.Parameters.Add("@TenantID", SqlDbType.Int).Value = 1;
                cmd.Parameters.Add("@Questions", SqlDbType.VarChar).Value = txtNewQuestion.Text;
                cmd.Parameters.Add("@QuestionType", SqlDbType.VarChar).Value = ddlNewQuestionType.Text;
                cmd.Parameters.Add("@AudioPath", SqlDbType.VarChar).Value = txtNewAudioPath.Text;
                cmd.Parameters.Add("@QuestionStatus", SqlDbType.Int).Value = Int32.Parse(rdoNewQuestionStatus.SelectedItem.Value);
                cmd.Parameters.Add("@DataType", SqlDbType.VarChar).Value = ddlNewQuestionDataType.Text;
                cmd.Parameters.Add("@UserField", SqlDbType.VarChar).Value = ddlNewUserField.Text;
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception err)
            {
                Response.Write(err.Message);
            }
            finally
            {
                con.Close();
            }
            //string type = Page.Request.Form["hdnAddQuestionField"].ToString();
           // if (type == "Security Question")
            //    getSecurityQuestions();
            //if (type == "Personal Identity")
            //    getPersonalIdentityQuestions();
            //if (type == "Past History")
           //     getPastHistoryQuestions();
            txtNewQuestion.Text = string.Empty;
            ddlNewQuestionType.Text = string.Empty;
            txtNewAudioPath.Text =string.Empty;
            rdoNewQuestionStatus.SelectedItem.Value = string.Empty;
            ddlNewQuestionDataType.Text = string.Empty;
            ddlNewUserField.Text = string.Empty;

        }

按下F5时如何防止重复插入

避免此问题的一种方法是在发布后重定向到同一页面(Response.Redirect("[current_url]"))。这种模式被称为PRG(发布/重定向/获取)。通过这种方式,浏览器刷新将在POST后导致GET,从而避免那些有问题的重复提交。

有关此模式的更多详细信息,请点击此处