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

时间:2013-06-29 02:47:47

标签: c# asp.net .net

在下面的代码中,iam执行在db.Everything中插入值的功能。工作正常但事情是如果我按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;


        }

1 个答案:

答案 0 :(得分:2)

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

有关此模式的更多详细信息here

相关问题