简体   繁体   English

页面刷新问题(F5)

[英]Page Refresh Issue (F5)

I have a page on which i have only one TextBox say Comments and Post Comment Button. 我有一个页面,在该页面上我只有一个TextBox说“ 注释”和“ 后置注释按钮”。

Now during input user write something in Comments textbox and press Post Comment button. 现在,在输入用户在“注释”文本框中写入内容并按“发表评论”按钮。 Whatever is written in the textbox all get stored in database and i clear the textbox with 无论在文本框中写什么都存储在数据库中,我清除文本框

textbox.text = string.empty statement.

After this user press F5 without doing anything and the same comment which i have already cleared gets stored in the database again. 在此用户之后按F5而不做任何事情,我已经清除的相同注释再次存储在数据库中。 I want to keep track of this thing that when button event is fired on F5 should not do anything. 我想跟踪一下在F5上触发按钮事件时不应执行任何操作。 please help in this. 请帮忙。

Make sure you're doing the database insert on an event handler for the Post Comment button. 确保您在“发表评论”按钮的事件处理程序上进行数据库插入。 If you're doing it in Page_Load , or some other method that's called by the framework on every rendering of the page, then this would result in the duplicate inserts you're seeing. 如果是在Page_Load执行此操作,或者是框架在每次页面渲染时调用了其他方法,则这将导致您看到的重复插入。

You may want to read up on the Post/Redirect/Get Pattern . 您可能想阅读Post / Redirect / Get Pattern

After performing the database submission you need to send a redirect back to the user which causes the browser to make a second request and eliminates the possibility of a duplicate post back if they refresh the browser. 执行数据库提交后,您需要将重定向发送回用户,这会导致浏览器发出第二个请求,并且如果刷新浏览器,则可以消除重复回发的可能性。 The redirect URL can be the same page you started on which you noted is one of the requirements. 重定向网址可以是您开始注册的同一页面,也是其中一项要求。

插入数据库后,重定向到另一个页面。

This is a browser's issue. 这是浏览器的问题。 You click on your button and save data into DB in your button's handler but when you is clicking F5 after, browser asks you (not all browsers is asking): do you want to send same postback? 您单击按钮并将数据保存到按钮处理程序中的数据库中,但是当您点击F5之后,浏览器会询问您(并非所有浏览器都在询问):您是否要发送相同的回发消息? You say Yes and browser sends same postback with same information to server. 你说是,浏览器服务器发送相同的回发信息 Server checks this postback and does Post Comment action where you save info into DB again. 服务器检查此回发,并执行“发表评论”操作,在此将信息再次保存到数据库中。

Most simple solution (after Redirect) is using Session variable to count number of "post backs": 最简单的解决方案(在重定向之后)是使用Session变量计算“回发”的数量:

int postBackCount = (Session["postbacks"] == null) ? 0 : (int)Session["postbacks"];
if (Page.IsPostBack) {
    if (postBackCount >= 1) {
        lbError.Text = "Can't submit this more than once, sorry";
    }
    else {
        //do DB stuff here.....
    }
    Session["postbacks"] = postBackCount + 1;
}
else {
    Session["postbacks"] = 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM