H. Senkaya
H. Senkaya

Reputation: 773

displaying loading spinner while jquery calls Controller in ASP.NET MVC

I have a jquery function in my View(Index.cshtml)...

<script type="text/javascript">
    // call ASP.NET MVC Controller and return value of Checkboxes as string array
    function SerializeMappings()
    {
        var matches = [];

        $('[class^="mappings_"]:checked').each(function () {
            matches.push(this.value);
        });

        $.post("/Home/Validate", { listofmappings: matches }, function (data) {
            document.write(data);
        });
    }
</script>

This function calls this function:

    // POST: Home/Validate
    [HttpPost]
    public ActionResult Validate(string[] listOfMappings)
    {
       //Some code which takes Long time (~10-15sec)
       //....
       //fill List<List<string>> with data and return it to Validate.cshtml

       return View(anyStringList);
    }

Now my real question: How can I display a loading circle while the 'Validate' function is running...? Thanks in advance.

Upvotes: 1

Views: 1733

Answers (1)

user449689
user449689

Reputation: 3154

You have some different approaches.


The basic one is to show the spinner just before the post and hide it when the call is ended, as follows:

// Here you show the spinner
...
$.post("/Home/Validate", { listofmappings: matches }, function (data) {
    document.write(data);
})
.always(function() {
    // Here you hide the spinner
    ...
});;


Another approach, if you are using a layout and you want to standardize and centralize the management of the spinner is to use jQuery Global Ajax Event Handlers.

First you let jQuery know that when you launch an Ajax request you want to show the spinner that will be located in your layout:

$.ajaxSetup({
    beforeSend: function () {
        // Here you show your spinner
        ...
    }
});

When every request is completed, you just hide the spinner:

$(document).ajaxComplete(function () {
    // Here you hide the spinner
    ...
});

The same thing can be accomplished as Azim suggested in his comment, using ajaxStart and ajaxStop.

Upvotes: 3

Related Questions