ASP.NET MVC 5: Button Loader Integration

User interaction & responsiveness are major aspects in any application. It is always good to tell the user that is happening in the application i.e. whether they have to wait for certain processing or they can proceed with another action,  etc.

Today, I shall be demonstrating the integration of a simple button loader plugin called Ladda, you can explore it more by visiting the website.

design

You can download the complete source code for this tutorial from here or you can follow step by step discussion below. The sample code is developed in Microsoft Visual Studio 2013 Ultimate.

Let's begin now:

  1. Create new MVC web project and name it "ButtonLoader".

  2. Download the Ladda plugin and incorporate its related JavaScript & CSS files into the project.

  3. Create new controller under "Controller" folder and name it "LoaderController.cs".

  4. Open "RouteConfig.cs" file under "App_Start" folder and change the default controller to "Loader" and action to "Index" as shown below.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. using System.Web.Routing;  
    7. namespace ButtonLoader  
    8. {  
    9.     public class RouteConfig  
    10.     {  
    11.         public static void RegisterRoutes(RouteCollection routes)  
    12.         {  
    13.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
    14.             routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new  
    15.             {  
    16.                 controller = "Loader", action = "Index", id = UrlParameter.Optional  
    17.             });  
    18.         }  
    19.     }  
    20. }  
  5. Create new file "LoaderViewModels.cs" under "Models" folder and place the following code in it:
    1. using System.ComponentModel.DataAnnotations;  
    2. namespace ButtonLoader.Models  
    3. {  
    4.     public class LoaderViewModel  
    5.     {  
    6.         [Required]  
    7.         [Display(Name = "Text")]  
    8.         public string Text  
    9.         {  
    10.             get;  
    11.             set;  
    12.         }  
    13.     }  
    14. }  
    Here, we have created a simple model for observing our loader effect.

  6. Now, open "LoaderController.cs" file under "Controller" folder and replace it with the following code:
    1. //-----------------------------------------------------------------------   
    2. // <copyright file="LoaderController.cs" company="None">  
    3. // Copyright (c) Allow to distribute this code.   
    4. // </copyright>  
    5. // <author>Asma Khalid</author>  
    6. //-----------------------------------------------------------------------   
    7. namespace ButtonLoader.Controllers  
    8. {  
    9.     using System;  
    10.     using System.Collections.Generic;  
    11.     using System.Linq;  
    12.     using System.Security.Claims;  
    13.     using System.Threading;  
    14.     using System.Threading.Tasks;  
    15.     using System.Web;  
    16.     using System.Web.Mvc;  
    17.     using ButtonLoader.Models;  
    18.     /// <summary>  
    19.     /// Loader controller class.   
    20.     /// </summary>  
    21.     public class LoaderController: Controller  
    22.     {  
    23.         #region Index view method.#region Get: /Loader/Index  
    24.         method.  
    25.             /// <summary>  
    26.             /// Get: /Loader/Index method.   
    27.             /// </summary>  
    28.             /// <returns>Return index view</returns>  
    29.         public ActionResult Index()  
    30.         {  
    31.             try  
    32.             {}  
    33.             catch (Exception ex)  
    34.             {  
    35.                 // Info   
    36.                 Console.Write(ex);  
    37.             }  
    38.             // Info.   
    39.             return this.View();  
    40.         }#endregion# region POST: /Loader/Index  
    41.             /// <summary>  
    42.             /// POST: /Loader/Index   
    43.             /// </summary>  
    44.             /// <param name="model">Model parameter</param>  
    45.             /// <returns>Return - Loader content</returns>  
    46.             [HttpPost]  
    47.             [AllowAnonymous]  
    48.             [ValidateAntiForgeryToken]  
    49.         public ActionResult Index(LoaderViewModel model)  
    50.         {  
    51.             try  
    52.             {  
    53.                 // Verification   
    54.                 if (ModelState.IsValid)  
    55.                 {  
    56.                     // Sleep.   
    57.                     Thread.Sleep(5000); // 5 sec.   
    58.                     // Info.   
    59.                     return this.Json(new  
    60.                     {  
    61.                         EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text  
    62.                     });  
    63.                 }  
    64.             }  
    65.             catch (Exception ex)  
    66.             {  
    67.                 // Info   
    68.                 Console.Write(ex);  
    69.             }  
    70.             // Sleep.   
    71.             Thread.Sleep(5000); // 5 sec.   
    72.             // Info   
    73.             return this.Json(new  
    74.             {  
    75.                 EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later"  
    76.             });  
    77.         }#endregion# endregion  
    78.     }  
    79. }  
    In the above code snippet, we have created a simple "HttpGet" & "HttpPost" methods to observer the behavior of the button loader. We have also placed a 5 sec delay in the post method at every response to observer the behavior of the button loader from server side as well.

  7. Now, in "Views->Loader" folder create a new page called "Index.cshtml" and place the following code in it:
    1. @using ButtonLoader.Models   
    2. @model ButtonLoader.Models.LoaderViewModel   
    3. @{   
    4. ViewBag.Title = "ASP.NET MVC5 C#: Button Loader Integration";   
    5. }   
    6.   
    7. <div class="row">  
    8.     <div class="panel-heading">  
    9.         <div class="col-md-8">  
    10.             <h3>  
    11.                 <i class="fa fa-file-text-o"></i>  
    12.                 <span>Bootstrap Modal with ASP.NET MVC5 C#</span>  
    13.             </h3>  
    14.         </div>  
    15.     </div>  
    16. </div>  
    17. <div class="row">  
    18.     <section class="col-md-4 col-md-push-4">  
    19.         @using (Ajax.BeginForm("Index""Loader"new AjaxOptions { HttpMethod = "POST", OnSuccess = "onLoaderSuccess" }, new { @id = "LoaderformId", @class = "form-horizontal", role = "form" }))   
    20.         {   
    21.             @Html.AntiForgeryToken()   
    22.   
    23.         <div class="well bs-component">  
    24.             <br />  
    25.             <div class="row">  
    26.                 <div class="col-md-12 col-md-push-2">  
    27.                     <div class="form-group">  
    28.                         <div class="col-md-10 col-md-pull-1">  
    29.                             @Html.TextBoxFor(m => m.Text, new { placeholder = Html.DisplayNameFor(m => m.Text), @class = "form-control" })   
    30.                             @Html.ValidationMessageFor(m => m.Text, ""new { @class = "text-danger custom-danger" })   
    31.                         </div>  
    32.                     </div>  
    33.                     <div class="form-group">  
    34.                         <div class="col-md-18"></div>  
    35.                     </div>  
    36.                     <div class="form-group">  
    37.                         <div class="col-md-4 col-md-push-2">  
    38.                             <div >  
    39.                                 <button type="submit"   
    40.                                     class="btn btn-warning ladda-button"   
    41.                                     value="Process"   
    42.                                     data-style="slide-down">  
    43.                                     <span class="ladda-label">Process</span>  
    44.                                 </button>  
    45.                             </div>  
    46.                         </div>  
    47.                     </div>  
    48.                 </div>  
    49.             </div>  
    50.         </div>  
    51. }   
    52.   
    53.     </section>  
    54. </div>  
    In the above code snippet, we have created a simple text input box and a button, for Ladda plugin to work however, you have to use following structure on button i.e.
    1. <button type="submit" class="btn btn-warning ladda-button" value="Process" data-style="slide-down">  
    2.     <span class="ladda-label">Process</span>  
    3. </button>  
    Unfortunately, Ladda plugin does not work with input type buttons.

  8. Under "Scripts" folder, create a new script called "custom-loader.js" and place the following code in it:
    1. $(document).ready(function()  
    2. {  
    3.     Ladda.bind('.ladda-button');  
    4.     $("#LoaderformId").submit(function(event)  
    5.     {  
    6.         var dataString;  
    7.         event.preventDefault();  
    8.         event.stopImmediatePropagation();  
    9.         var action = $("#LoaderformId").attr("action");  
    10.         // Setting.   
    11.         dataString = new FormData($("#LoaderformId").get(0));  
    12.         contentType = false;  
    13.         processData = false;  
    14.         $.ajax(  
    15.         {  
    16.             type: "POST",  
    17.             url: action,  
    18.             data: dataString,  
    19.             dataType: "json",  
    20.             contentType: contentType,  
    21.             processData: processData,  
    22.             success: function(result)  
    23.             {  
    24.                 // Result.   
    25.                 onLoaderSuccess(result);  
    26.             },  
    27.             error: function(jqXHR, textStatus, errorThrown)  
    28.             {  
    29.                 //do your own thing   
    30.                 alert("fail");  
    31.                 // Stop Button Loader.   
    32.                 Ladda.stopAll();  
    33.             }  
    34.         });  
    35.     }); //end .submit()   
    36. });  
    37. var onLoaderSuccess = function(result)  
    38. {  
    39.     if (result.EnableError)  
    40.     {  
    41.         // Clear.   
    42.         $('#ModalTitleId').html("");  
    43.         $('#ModalContentId').html("");  
    44.         // Setting.   
    45.         $('#ModalTitleId').append(result.ErrorTitle);  
    46.         $('#ModalContentId').append(result.ErrorMsg);  
    47.         // Show Modal.   
    48.         $('#ModalMsgBoxId').modal(  
    49.         {  
    50.             backdrop: 'static',  
    51.             keyboard: false  
    52.         });  
    53.     }  
    54.     else if (result.EnableSuccess)  
    55.     {  
    56.         // Clear.   
    57.         $('#ModalTitleId').html("");  
    58.         $('#ModalContentId').html("");  
    59.         // Setting.   
    60.         $('#ModalTitleId').append(result.SuccessTitle);  
    61.         $('#ModalContentId').append(result.SuccessMsg);  
    62.         // Show Modal.   
    63.         $('#ModalMsgBoxId').modal(  
    64.         {  
    65.             backdrop: 'static',  
    66.             keyboard: false  
    67.         });  
    68.         // Resetting form.   
    69.         $('#LoaderformId').get(0).reset();  
    70.     }  
    71.     // Stop Button Loader.   
    72.     Ladda.stopAll();  
    73. }  
    I have also combined modal here to display server response. The following piece of code will bind the button loader plugin with the button i.e.
    1. Ladda.bind('.ladda-button');   
    So, whenever, I click the button the button loader will start. The following piece of code will stop the button loader effect whenever I receive a response from the server side:
    1. // Stop Button Loader.   
    2. Ladda.stopAll();   
  9. Now, execute the application and you can see the following:

    see run
    Output

    run

Conclusion

In this tutorial you learned how to enhance user interactivity of a MVC base web application by integrating button loader plugin and you also learned how to combine button loader effect with server side response.

Read more articles on ASP.NET: