我有一个asp.net控件,在页面刷新时似乎会触发按钮单击事件处理程序。这是为什么,我该如何避免?
另外一种方法,这对我很有效 -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
protected override void OnPreRender(EventArgs e)
{
ViewState["update"] = Session["update"];
}
protected void btnProceed_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString())
DisplayInfo();
}
private void DisplayInfo()
{
// Do what ever thing you want to do
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
see This for more details
//Web browser refresh fires the last event (ex. button click) again.
//the following code prevents this action by detecting the Page refresh.
if (!IsPostBack)
{
ViewState["postGuids"] = System.Guid.NewGuid().ToString();
Session["postGuid"] = ViewState["postGuids"].ToString();
}
else
{
if (ViewState["postGuids"].ToString() != Session["postGuid"].ToString())
{
IsPageRefresh = true;
}
Session["postGuid"] = System.Guid.NewGuid().ToString();
ViewState["postGuids"] = Session["postGuid"].ToString();
}
protected void Button_Click(object sender, EventArgs e)
{
if (!IsPageRefresh) //only perform the button click actions if page has not been refreshed
{
//Normal actions as per button click
}
}
我不确定像上面这样的任何服务器代码如何应对检测到重复刷新,如果用户看到意外情况可能会这样做。我尝试过这种方法,但浪费了一个小时左右,最终决定避免这种情况的最简单方法是在事件按钮的代码后端使用Response.Redirect(HttpContext.Current.Request.Url.ToString(), True)重新加载页面。我认为这可能会导致额外的网络流量,但它很简单。