Prevent the button from being clicked while the update is in progress using ASP.net

When using ASP.NET Ajax to load large amounts of data on button click in a grid view, it's important to display a loading message during the update progress. In this scenario, the BtnLoadReport Button needs to be disabled.

<td>
     <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
</td>
<td>
   &nbsp;</td>
<td>
 &nbsp;</td>
</tr>
  <tr>
    <td>
     <asp:UpdateProgress ID="updProgress"
        AssociatedUpdatePanelID="UpdatePanel1"
        runat="server" oninit="updProgress_Init" onprerender="updProgress_PreRender">
            <ProgressTemplate>            
               <span style="color:green; font-style:italic;">Loading, please wait...</span>            
            </ProgressTemplate>
        </asp:UpdateProgress>
                        <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
                        <ContentTemplate>
                        <div id="DemoId">
                          <asp:Button ID="BtnLoadReport" runat="server" onclick="BtnLoadReport_Click" 
                Text="LoadReport" Width="176px"  ClientIDMode="Static" OnClientClick="return clickOnLoadReport();" />
                </div>
                           <asp:GridView ID="GridView1" runat="server" Height="170px" 
                    onselectedindexchanged="GridView1_SelectedIndexChanged" Width="438px">
                 </asp:GridView>
                        </ContentTemplate>
                        <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="BtnLoadReport" EventName="Click" />
                        </Triggers>
                        </asp:UpdatePanel>
                    </td>
                    <td>
                        &nbsp;</td>
                    <td>
                        &nbsp;</td>
                </tr>
            </table>

Below is the script used to disable the button:

          <script type="text/javascript">
            var updateProgress = null;
               function clickOnLoadReport() {
              var prm = Sys.WebForms.PageRequestManager.getInstance();
              if (prm.get_isInAsyncPostBack()==false) {
              var nodes = document.getElementById("DemoId").getElementsByTagName('*');
               for (var i = 0; i < nodes.length; i++) {
                nodes[i].disabled = true;
               }
             }
            }
          </script>

However, some users have reported that the button is only disabled for a brief moment instead of for longer periods as intended.

  protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(this.BtnLoadReport);
        }

        protected void BtnLoadReport_Click(object sender, EventArgs e)
        {
                UpdatePanel1.Update();
                DataSet dataSet = new DataSet();
                dataSet.ReadXml(@"C\Data.Xml");
                GridView1.DataSource = dataSet.Tables[0];
                GridView1.DataBind();

        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void updProgress_Init(object sender, EventArgs e)
        {
BtnLoadReport.Enable = false;        
        }

        protected void updProgress_PreRender(object sender, EventArgs e)
        {
           BtnLoadReport.Enable
 = true;
        }

The above code attempts to dynamically enable and disable the BtnLoadReport button during the update progress, but there seem to be issues with retaining the disabled state. Any help or suggestions would be greatly appreciated.

Answer №1

function updateLoadReportFunction() {
        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        requestManager.add_initializeRequest(CancelPostbackForSubsequentSubmitClicks);

        function CancelPostbackForSubsequentSubmitClicks(sender, args) {
            if (requestManager.get_isInAsyncPostBack() &
        args.get_postBackElement().id == 'BtnLoadReport') {
                args.set_cancel(true);
                document.getElementById("BtnLoadReport").setAttribute("disabled", "disabled");
                //alert('A previous request is still in progress that was issued on clicking ' + args.get_postBackElement().id);
            }
        }
    }

i updated my javascript function and it successfully resolved the issue

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing checked checkboxes in an Asp.net Page using C#: A simple guide to maintaining a list

I have a program that dynamically adds multiple checkboxes. When a checkbox is clicked, a method is triggered to either add it to or remove it from a predefined list based on its checked status. The issue I'm encountering is that the list appears to ...

Creating a recursive function in JavaScript to build a menu list object

Having an assortment of ['/social/swipes/women', '/social/swipes/men', '/upgrade/premium']; The objective is to create a map object that mirrors this structure: { 'social': { swipes: { wom ...

Challenges with Parsing JSON Data

I have a challenge with using newtonsoft.json to deserialize a json string from the White Pages Pro API. The deserialization process was smooth until I reached the 'is_commercial' field, everything after that is giving me errors. The specific err ...

Regain focus after selecting a date with Bootstrap datepicker

When initializing a bootstrap datepicker from eternicode with the parameter autoclose: true, there are two undesired behaviors that occur: After closing the picker, tabbing into the next field causes you to start at the beginning of the document again, w ...

I am facing errors while running npm run build in my Vue CLI project, however, npm run dev is running smoothly without

I am encountering an issue when running npm run build as it generates a series of errors, whereas npm run dev runs smoothly without any errors. I have attempted to resolve this by modifying the public path in webpack.config.js to ./dist, but unfortunately ...

Add an element to an array using a dynamic variable as the key

I'm encountering an issue with a JavaScript array and a variable. My goal is to add to the array an object where the property name corresponds to the variable, but it should hold the value of that variable rather than treating it as a string. Here&apo ...

Encountering issues with parsing a JSON object while utilizing the templateHTMLrenderer feature in Django

I'm just starting out with django and JSON, and I'm attempting to send a list of patients in JSON using the code below: class JSONResponse(HttpResponse): """ An HttpResponse that converts content into JSON format. """ def __init_ ...

What is the best way to verify the presence of an Object within a JObject and append a new Object if it does not already exist, or merge it with the existing Object

I'm currently working on a solution to verify the presence of Object "key6" within the JSON data displayed below: { "key1": "www.microsoft0nline.nl/test.php", "key2": "2019-06-05 11:21:09", "key3": "otherValue1", "key4": "433", "key5": ...

how to use c# to send email

When attempting to send an email using the following code snippet, I encountered an error at smtp.Send(mail), with the message "Failure sending mail": MailMessage mail = new MailMessage(); // set the addresses mail.From = new MailAddress("example@ ...

The validation functionality in AngularJS for a form within an ng-repeat loop is not functioning as intended

In my table, I used the <tr> tag repeatedly with ng-repeat="cancellationPercentData in cancellationPercent" Each tr tag contains a form with name and id set using $index See the code snippet below: <tbody> <tr ng-repeat="cancellatio ...

What is the most efficient method for managing components with dynamic templates and their corresponding data in Vue.js?

I have a question and requirement that I would like to discuss. It involves dynamically rendering templates and data using components. The scenario is as follows: The root Vue instance fetches data from the backend, and let's say the following data i ...

Div keydown event not being triggered in Vue

I've been struggling to get my event to fire despite following the instructions in the title. @keydown="keyPressed($event)" Although currently it looks like this, I have also attempted setting the tabIndex and adding it on mount as shown be ...

Capturing logs while running a background task with Hangfire using NLog

Currently, I am facing an issue where the logging information from a method scheduled with Hangfire is not being captured as expected. The method in question performs logging using NLog, and when run without Hangfire, all the relevant logging information i ...

Error: You can't call .text as a function in jQuery

While trying to retrieve the text from my td, I encountered the following error: $tds[2].text is not a function. The output of console.log('td',$tds[2]) shows: https://i.stack.imgur.com/OUngP.png $(document).ready(function() { $trs = $(&ap ...

Navigating on a page using anchor tags within a dropdown menu

I'm in the process of creating a top navigation bar with dropdown functionality that appears when hovering over certain navigation items. Here's how it currently looks: $(document).ready(function(){ $('[data-toggle="tooltip"]').t ...

Issue encountered in transferring Json data from controller to view, Laravel version 5.6

I'm struggling to convert the Json value received from my controller into a properly readable JavaScript value. This is my controller: $room = Room:: select('id', 'name', 'capacity', 'status') ...

Prevent the href from navigating to the next page when a doubleclick event listener is triggered

In my project, I am using an anchor tag that redirects to another page. However, if the user double clicks on it, I want to prevent the default behavior and stop the redirection. <a href="{location}">My Link</a> element.addEventListen ...

Is there a way for mocha to conduct a recursive search within my `src` directory in order to find a specific

In my npm project, I want to replicate the structure used by Meteor: there is a source file called client.js and its corresponding test file named client.tests.js residing in the src/ directory. The tests should be executed with the npm test command. I am ...

Difference between casting to UInt16 and using Convert.ToUInt16(i)

I possess an Int32 situated within the limits of UInt16. Which technique is best suited to transform it into an UInt16? Is there a particular advantage to using one method over the other or are they essentially interchangeable? Are there any potential is ...

Forwarding requests from a C# WebApi to a different domain

Our goal is to direct all C# WebApi traffic from domain A to domain B: For example, we want: GET https://www.billiving.com/api2/v1/invoices routed to: GET https://api.billiving.com/v1/invoices POST https://www.billiving.com/api2/v1/invoices routed to: P ...