【问题标题】:How to focus a error after disable button 1st click using asp.net?使用asp.net禁用按钮第一次单击后如何聚焦错误?
【发布时间】:2017-01-16 10:58:11
【问题描述】:

我在 asp.net 中编写了第一次单击后禁用按钮的代码。代码如下:

<asp:Button ID="btnNext" runat="server" CssClass="btn btnBlue btnStep" Text="Submit" 
                OnClick="btnSubmit_Click" CausesValidation="true" ValidationGroup="ServiceFee" OnClientClick="this.disabled = true; this.value = 'In progress...';__doPostBack('btnNext','')" UseSubmitBehavior="false" />

它工作正常没问题,但现在我需要添加一些额外的功能,即我需要专注于错误。当用户在没有输入卡片详细信息或个人详细信息的情况下点击提交按钮时,它会在空白文本框中显示错误并且突然页面会重新加载,因为 我已经用 javascript 编写了 dopostback。 那么如何关注错误以及之后回发需要显示错误?

【问题讨论】:

  • 进行ajax调用并检查是否成功,如果失败,您可以在页面上显示您的验证消息或失败原因而无需重新加载。

标签: javascript c# jquery asp.net


【解决方案1】:

btnNext 事件中你可以有类似的东西

// Supose txtCardDetails is the TextBox with the card details
if (string.IsNullOrWhiteSpace(txtCardDetails.Text))
{
    ClientScript.RegisterStartupScript(this.GetType(), "script", "document.getElementById('" + txtCardDetails.ClientID + "').focus();");
    return; // Maybe you want to do something before leave the event method
}

这将发送一个脚本来聚焦字段,但是,我建议在客户端 (JS) 和服务器端 (C#) 进行验证,所以,在客户端验证这个应该是这样的

<asp:Button ID="btnNext" runat="server" ... 
            OnClientClick="return SubmitIfValid(this);" ...  />


function SubmitIfValid(el) {
   if(document.getElementById('<%= txtCardDetails.ClientID %>').value === ''){
      alert('invalid card details');
      document.getElementById('<%= txtCardDetails.ClientID %>').focus();
      return false;
   }

   // more validations

   // if all is OK then...
   el.disabled = true; 
   el.value = 'In progress...';
   __doPostBack('btnNext','')
   return true;
}   

【讨论】:

    【解决方案2】:

    您可以使用validationSummary 等验证控件。自己管理此类错误可能非常困难。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多