• asp.net防止刷新时重复提交


    前段时间遇到了需要禁用刷新的需求,f5按钮就不说了,简单的js就能把它禁用,但是工具条上的刷新按钮却傻傻干不掉。

    如果简单的在刷新时重新加载画面,通过window.location.href="url"可以很容易的实现,但是需求是要求在刷新时什么都不做,保留画面的状态,这下子可就复杂化了。

    asp.net中分辨请求是重新请求还是通过刷新按钮再次请求不是很方便,为了实现这个效果,试过了很多的方式,一下面的两种为例

    1.

    private bool pageRefreshed = false; //页面是否刷新提交
    private bool refreshState = false;  //ViewState中暂存的状态

        然后重写Page的LoadViewState与SaveViewState方法:

    protected override void LoadViewState(object savedState)
    {
        object[] states = (object[])savedState;
        base.LoadViewState(states[0]);
        refreshState = (bool)states[1];
        if(Session["__PAGE_REFRESHED"] == null)
            pageRefreshed = false;
        else
            pageRefreshed = refreshState != (bool)Session["__PAGE_REFRESHED"];
    }
    
    protected override object SaveViewState()
    {
        Session["__PAGE_REFRESHED"] = !refreshState;
        object[] states = new object[2];
        states[0] = base.SaveViewState();
        states[1] = !refreshState;
        return states;
    }
    private void Button1_Click(object sender, EventArgs e)
    {
     if (pageRefreshed )
                {
                   label.Text="this is refreshed function";
                }
    else
    {
      label.Text="this is new request function";
    }
    }

    这种方法虽然能够实现,但是在某些请款下不适应。如果画面上同时存在文本框和按钮式,设置按钮的autopostback="True"时,在修改完文本框的值,直接点击按钮(在文本框没有失去焦点时,直接点击按钮),这时的执行顺序是textchanged→textchanged→buttonclick,在第一次textchanged时,就把状态已经变成了true,按钮的不能执行。

    2.codeproject找到了另外一种解决方法 原文地址:http://www.codeproject.com/Articles/18841/Refresh-Module

    这种方式能够准确的判断是否是通过浏览器的刷新按钮进行的请求,而且使用起来也非常简单!

    1.引用dll,修改配置文件

    在配置文件中添加modules

    <system.web>
        <httpModules>
            <add name="RefreshModule" 
                type="RefreshModule.Module, RefreshModule"/>
        </httpModules>
    </system.web> 

    PS:wbapplication的情况下需要改成在system.webServer的modules的节点下追加modules

    2.定义刷新时的行为

    [Refresh()]
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
             if(IsPostBack && !RefereshHelper.IsPageRefreshed)
            {
                // do some work with the submitted date
            }
            else
            {
                
               // do some work when the page is loaded with the GET method
            }
        }
    }
    RefereshHelper.IsPageRefreshed这个参数就是用来判断是否是通过浏览器的书刷新按钮进行的请求。
    其他的行为行为控制参照原文。
    PS:codeproject真是个不过的地方,很多问题都是通过它来解决的

    其他的方式不一一列举,列举的第二种方式可以说简单易用,所有的实现都已经为我们封装好了,只需要简单的调用。

  • 相关阅读:
    二分查找
    django 中间件
    logging 模块
    linux ssh keys
    spark(一) build
    hadoop中遇到的问题。
    算法----字符串拷贝
    phpmailer 实现发送邮件
    thinkphp操作数据库
    thinkphp 使用过程中遇到的一个小函数
  • 原文地址:https://www.cnblogs.com/qiangwei/p/disabledRefreshButton.html
Copyright © 2020-2023  润新知