Запрет POST BACK, когда он уже выполняется - PullRequest
1 голос
/ 21 июля 2010

Отключить пост обратно из asp.net, т.е. кнопки, ссылки, изменение индекса страницы сетки, сортировку и т. Д., Когда пост уже выполняется. Целевой браузер - IE 6+. Я написал эти 2 javascript, я не уверен, как применять его при изменении индекса страницы GridView.

<script type="text/javascript">
          //isFormSubmitted variable is used to prevent the form submission while the server execution is in progress
          var isFormSubmitted = false;
          //If the form is already submitted, this function will return false preventing the form submission again.
          function SubmitForm(msg)
          {
            try {
             if(isFormSubmitted == true)
             {
               alert('A post back is already in progress. Please wait');
               return false; 
             }
             else 
             {
               var res = false;
               if (msg)
               {
                 res = confirm(msg);
               }
               if (res == true)
               {  
                 isFormSubmitted = true;
               }
               return res;
             }
           } catch(ex) {}
          }

          function VerifySubmit()
          {
             if(isFormSubmitted == true)
             {
               alert('A post back is already in progress. Please wait');
               return false; 
             }
             else 
             {
               isFormSubmitted = true;
               return true;
             }
          } 
</script>

Для кнопок я могу прикрепить SubmitForm к OnClientClick следующим образом.

<asp:Button ID="btnCancel" runat="server" CssClass="button" Text="Cancel" OnClick="btnCancel_Click" OnClientClick="return SubmitForm('Do you want to continue with cancelling recent action?');" />

Но я не уверен, как подключить VerifySubmit к элементам управления без подсказок, таким как пейджер gridview.

Ответы [ 4 ]

2 голосов
/ 21 июля 2010
 onclick="this.disabled=true;"

на вашей кнопке отправки есть весь необходимый вам "магический" javascript

Когда jQuery - опция, вы можете использовать этот небольшой скрипт, чтобы отключить все кнопки отправки:

// Find ALL <form> tags on your page
$('form').submit(function(){
    // On submit disable its submit button
    $('input[type=submit]', this).attr('disabled', 'disabled');
});

Найдено здесь: http://jquery -howto.blogspot.com / 2009/05 / disable-submit-button-on-form-submit.html

Или вы можете заблокировать всю страницу: http://jquery.malsup.com/block/#page

1 голос
/ 21 июля 2010

Я собираюсь предположить, что вы здесь делаете вещи типа ajaxy, и у вас идет асинхронная обратная передача, и вы не хотите, чтобы пользователь нажимал кнопку в это время.в этом случае попробуйте следующий код:

    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(startRequest);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);

    function startRequest(sender, e) {
        //disable search button during the AJAX call
        document.getElementById('<%=btnSearch.ClientID%>').disabled = true;

    }

    function endRequest(sender, e) {
        //re-enable the search button once the AJAX call has completed
        document.getElementById('<%=btnSearch.ClientID%>').disabled = false;
    }
1 голос
/ 21 июля 2010

Если вы хотите отключить постбэк, установите autopastback=false для кнопок ссылок.В противном случае вам нужно предоставить нам больше информации и более подробные инструкции / подробности, чтобы помочь вам.

0 голосов
/ 24 июля 2010

Самое простое решение, которое я нашел, это то, что ..

//In the head section define this script...

    <script type="text/javascript">
      function ShowProcessingMsg(confirmMsg) {
        var resp = confrim(confirmMsg);
        try {
          if (resp == true) {
            var divC = document.getElementById('<%= divControls.ClientID %>');
            var divM = document.getElementById('<%= divProcessingMsg.ClientID %>');
            if (divC && divM) {
              divC.display = "none";
              divM.display = "block";
            }
            else {
              return false;
            }
          }
        } catch (exp) { alert(exp); return false; }
        return resp;
      }
    </script>

//This div will show during processing since by default it's display is none when after
//Post back your page loaded again this will not be diplayed. We are going to set it's
//diplay attribute to block from javascript.

<div id="divProcessingMsg" runat="server" display="none" z-index="1000" />
   <b>Processing.... Please wait.</b>
</div>


//We will hide this div from script by setting its display attribute to none. Since 
//by default this attribute is block when the page loaded again it'll be displayed by 
//default. So no special handling for setting display again to block is required.

<div id="divControls" runat="server" display="block" z-index="1" />
   <asp:GridView ............ >
   .....
   .....
   .....
   <asp:Button runat="server" id="btnProcess" Text="Process" OnClientClick="return ShowProcessingMsg('Do you want to continue with processing'); OnClick="btnProcess_ServerClick" />
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...