1

我需要知道如何防止用户多次提交表单并在 ASP.NET 中单击提交按钮后禁用它。禁用按钮后是否可以添加加载动画?我尝试了 OnClientClick 事件来禁用按钮,但取消了页面刚刚回发而没有任何更改的 OnClick 事件。有什么线索吗?

4

3 回答 3

3

尝试这个:

protected void Page_Load(object sender, EventArgs e)
{            
    Page.ClientScript.RegisterOnSubmitStatement(GetType(), "ServerForm",
        "if(this.submitted) return false; this.submitted = true;");
    button.Attributes.Add("onclick", string.Format("this.value='wait...';
        this.disabled=true; {0}", ClientScript.GetPostBackEventReference
        (button, string.Empty)));
}
于 2012-06-23T18:49:54.377 回答
0

您需要 _endRequest、_beginRequest 处理程序。在后面的代码中添加这个。

public object endRequestHandle { get; set; }

public object beginRequestHandle { get; set; }

在您的 aspx 页面中,添加以下内容:

 Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandle);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandle);
//Function gets called before Ajax request
            function beginRequestHandle(sender, Args) {
                $('#SubmitButton').attr("disabled", true);
                $('#LoadingImage').css("visibility","visible");
            }
    //Function gets called after Ajax request completes
            function endRequestHandle(sender, Args) {
              $('#SubmitButton').attr("enabled", true);
                $('#LoadingImage').css("visibility","invisible");
            }
于 2012-06-23T18:36:32.893 回答
0

我过去使用的一个解决方案是创建 System.Web.UI.WebControls.Button 的新子类,该子类使用 Javascript 在单击后禁用自身。请注意,您必须小心不要覆盖 ASP.NET 客户端验证代码。

如果您想在点击后添加加载动画,您可以通过validateAndDisableScript以下调整添加客户端 javascript 以显示先前隐藏的动画图标。

//
// This is a Button-derived class that will disable itself when it is clicked,
// preventing multiple submits of forms where necessary.
//
public class OneShotButton : System.Web.UI.WebControls.Button
{
    //
    // Javascript that invokes client validation (if enabled), and disables
    // the containing HTML element.  This script doesn't do the postback, so
    // that code has to be appended during OnPreRender.
    //
    private const string validateAndDisableScript =
        @"if ( typeof(Page_ClientValidate) == 'function' )" +
        @"{" +
        @"  if ( !Page_ClientValidate() ) { return false; }" +
        @"}" +
        @"this.disabled = true;";   // postback code follows


    //
    // Override OnPreRender to set Javascript associated with the onclick
    // event for this button.  Most of the Javascript is prebuilt, but we
    // have to dynamically generate the postback code.
    //
    protected override void OnPreRender(System.EventArgs e)
    {
        string onClick = string.Format("{0}{1};",
            validateAndDisableScript,
            Page.ClientScript.GetPostBackEventReference(this, string.Empty) 
            );

        Attributes.Add("onclick", onClick);

        base.OnPreRender(e);
    }
}
于 2012-06-23T17:39:54.500 回答