Home > Mobile >  Display a loader in ASP.NET MVC
Display a loader in ASP.NET MVC

Time:12-23

<body>
    <!-- my custom loader -->
    <div >
        <div id="preloaded">
            <div >
                <span></span>
                <span></span>
            </div>
        </div>

        <!-- other HTML -->
        <a id="btnId">Do something</a>

    </div>

    <script>
        $('#btnId') . on('click', function () {
            // start show my custom loader 
            // go to method in controller and do some thing
            // End show my custom loader
        });
    </script>
</body>

I can send data to method in controller by jQuery and get result but I want to show my custom loader when this process is in progress. I want only start and end show my loader.

Can anybody help me?

Thanks

CodePudding user response:

Your loader will either be a GIF image (animated), a div with some text in it or both. You can also position the div with the loader with position: absolute and a high z-index.

Displaying and hiding the loader is easy. Before the ajax Call you simply display, when the call is complete you hide it. Your view would look like this (without CSS):

<div >
    <div id="preloaded">
        <div >
            <span>Loading ...</span>
            <img src="@Url.Content("~/Path/ToMyImage.gif")" />
        </div>
    </div>

    <!-- other HTML -->
    <a id="btnId">Do something</a>

</div>

<script>
    $('#btnId') . on('click', function () {
        showLoader();
        ajaxCall();
    });

    function ajaxCall() {
        $.ajax({
            url: "@Url.Action("Action", "Controller")/",
            type: "post",
            data: jsonObject,
            success: function (response) {
                hideLoader();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert("An error occurred. Cannot complete the request!");
                hideLoader();
            }
        });
    }

    function showLoader() {
        $("#preloaded").css("display", "block");
    }

    function hideLoader() {
        $("#preloaded").css("display", "none");
    }
</script>

CodePudding user response:

CSS

.hide {
    visibility: hidden !important;
}

html

<div id="preloaded" >

JavaScript

 $('#btnId') . on('click', function () {
     document.querySelector('#preloaded').classList.remove('hide');

      $.ajax({ url: '../api/MyControllerApi/EndpointActionName',
            type: 'POST', data: myPayload, contentType:'application/json',
          success: function (data) {    
             document.querySelector('#preloaded').classList.add('hide');
            },
            error: function (xhr, response) {     
              document.querySelector('#preloaded').classList.add('hide');                         
            }
        });            
 });
  • Related