Sunday, 27 March 2016

User interaction & responsiveness are major aspects in any application. It is always  good to tell user that what 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 from visiting http://msurguy.github.io/ladda-bootstrap/ website.


Following are some prerequisites before you proceed further in this tutorial:

1) Knowledge of ASP.NET MVC5.
2) Knowledge of HTML.
3) Knowledge of JavaScript.
4) Knowledge of Ajax.
5) Knowledge of Bootstrap.
6) Knowledge of Jquery.
7) Knowledge of C# Programming.

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.

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using System.Web.Routing;  
 namespace ButtonLoader  
 {  
   public class RouteConfig  
   {  
     public static void RegisterRoutes(RouteCollection routes)  
     {  
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
       routes.MapRoute(  
         name: "Default",  
         url: "{controller}/{action}/{id}",  
         defaults: new { controller = "Loader", action = "Index", id = UrlParameter.Optional }  
       );  
     }  
   }  
 }  

5) Create new file "LoaderViewModels.cs" under "Models" folder and place following code in it:

 using System.ComponentModel.DataAnnotations;  
 namespace ButtonLoader.Models  
 {  
   public class LoaderViewModel  
   {  
     [Required]  
     [Display(Name = "Text")]  
     public string Text { get; set; }  
   }  
 }  

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 following code:

 //-----------------------------------------------------------------------  
 // <copyright file="LoaderController.cs" company="None">  
 //   Copyright (c) Allow to distribute this code.  
 // </copyright>  
 // <author>Asma Khalid</author>  
 //-----------------------------------------------------------------------  
 namespace ButtonLoader.Controllers  
 {  
   using System;  
   using System.Collections.Generic;  
   using System.Linq;  
   using System.Security.Claims;  
   using System.Threading;  
   using System.Threading.Tasks;  
   using System.Web;  
   using System.Web.Mvc;  
   using ButtonLoader.Models;  
   /// <summary>  
   /// Loader controller class.  
   /// </summary>  
   public class LoaderController : Controller  
   {  
     #region Index view method.  
     #region Get: /Loader/Index method.  
     /// <summary>  
     /// Get: /Loader/Index method.  
     /// </summary>      
     /// <returns>Return index view</returns>  
     public ActionResult Index()  
     {  
       try  
       {  
       }  
       catch (Exception ex)  
       {  
         // Info  
         Console.Write(ex);  
       }  
       // Info.  
       return this.View();  
     }  
     #endregion  
     #region POST: /Loader/Index  
     /// <summary>  
     /// POST: /Loader/Index  
     /// </summary>  
     /// <param name="model">Model parameter</param>  
     /// <returns>Return - Loader content</returns>  
     [HttpPost]  
     [AllowAnonymous]  
     [ValidateAntiForgeryToken]  
     public ActionResult Index(LoaderViewModel model)  
     {  
       try  
       {  
         // Verification  
         if (ModelState.IsValid)  
         {  
           // Sleep.  
           Thread.Sleep(5000); // 5 sec.  
           // Info.  
           return this.Json(new { EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text });  
         }  
       }  
       catch (Exception ex)  
       {  
         // Info  
         Console.Write(ex);  
       }  
       // Sleep.  
       Thread.Sleep(5000); // 5 sec.  
       // Info  
       return this.Json(new { EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later" });  
     }  
     #endregion  
     #endregion  
   }  
 }  

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 following code in it:

 @using ButtonLoader.Models  
 @model ButtonLoader.Models.LoaderViewModel  
 @{  
   ViewBag.Title = "ASP.NET MVC5 C#: Button Loader Integration";  
 }  
 <div class="row">  
   <div class="panel-heading">  
     <div class="col-md-8">  
       <h3>  
         <i class="fa fa-file-text-o"></i>  
         <span>Bootstrap Modal with ASP.NET MVC5 C#</span>  
       </h3>  
     </div>  
   </div>  
 </div>  
 <div class="row">  
   <section class="col-md-4 col-md-push-4">  
     @using (Ajax.BeginForm("Index", "Loader", new AjaxOptions { HttpMethod = "POST", OnSuccess = "onLoaderSuccess" }, new { @id = "LoaderformId", @class = "form-horizontal", role = "form" }))  
     {  
       @Html.AntiForgeryToken()  
       <div class="well bs-component">  
         <br />  
         <div class="row">  
           <div class="col-md-12 col-md-push-2">  
             <div class="form-group">  
               <div class="col-md-10 col-md-pull-1">  
                 @Html.TextBoxFor(m => m.Text, new { placeholder = Html.DisplayNameFor(m => m.Text), @class = "form-control" })  
                 @Html.ValidationMessageFor(m => m.Text, "", new { @class = "text-danger custom-danger" })  
               </div>  
             </div>  
             <div class="form-group">  
               <div class="col-md-18">  
               </div>  
             </div>  
             <div class="form-group">  
               <div class="col-md-4 col-md-push-2">  
                 <div >  
                   <button type="submit"  
                       class="btn btn-warning ladda-button"  
                       value="Process"  
                       data-style="slide-down">  
                     <span class="ladda-label">Process</span>  
                   </button>  
                 </div>  
               </div>  
             </div>  
           </div>  
         </div>  
       </div>  
     }  
   </section>  
 </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.

                  <button type="submit"  
                       class="btn btn-warning ladda-button"  
                       value="Process"  
                       data-style="slide-down">  
                     <span class="ladda-label">Process</span>  
                   </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 following code in it:

 $(document).ready(function ()  
 {  
   Ladda.bind('.ladda-button');  
   $("#LoaderformId").submit(function (event)  
   {  
     var dataString;  
     event.preventDefault();  
     event.stopImmediatePropagation();  
     var action = $("#LoaderformId").attr("action");  
     // Setting.  
     dataString = new FormData($("#LoaderformId").get(0));  
     contentType = false;  
     processData = false;  
     $.ajax({  
       type: "POST",  
       url: action,  
       data: dataString,  
       dataType: "json",   
       contentType: contentType,  
       processData: processData,  
       success: function (result)  
       {  
         // Result.  
         onLoaderSuccess(result);  
       },  
       error: function (jqXHR, textStatus, errorThrown)  
       {  
         //do your own thing  
         alert("fail");  
         // Stop Button Loader.  
         Ladda.stopAll();  
       }  
     });  
   }); //end .submit()  
 });  
 var onLoaderSuccess = function (result)  
 {  
   if (result.EnableError)  
   {  
     // Clear.  
     $('#ModalTitleId').html("");  
     $('#ModalContentId').html("");  
     // Setting.  
     $('#ModalTitleId').append(result.ErrorTitle);  
     $('#ModalContentId').append(result.ErrorMsg);  
     // Show Modal.  
     $('#ModalMsgBoxId').modal(  
       {  
         backdrop: 'static',  
         keyboard: false  
       });  
   }  
   else if (result.EnableSuccess)  
   {  
     // Clear.  
     $('#ModalTitleId').html("");  
     $('#ModalContentId').html("");  
     // Setting.  
     $('#ModalTitleId').append(result.SuccessTitle);  
     $('#ModalContentId').append(result.SuccessMsg);  
     // Show Modal.  
     $('#ModalMsgBoxId').modal(  
       {  
         backdrop: 'static',  
         keyboard: false  
       });  
     // Resetting form.  
     $('#LoaderformId').get(0).reset();  
   }  
   // Stop Button Loader.  
   Ladda.stopAll();  
 }  
 
I have also combined modal here to display server response. Following piece of code will bind the button loader plugin with the button i.e.

 Ladda.bind('.ladda-button');  

So, whenever, I click the button the button loader will start. Following piece of code will stop the button loader effect whenever I receive a response from the server side:

   // Stop Button Loader.  
   Ladda.stopAll();  

9) Now, execute the application and you will able to see following:





That's about.

Enjoy!! coding.

1 comments:


  1. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.

    Online Reputation Management

    ReplyDelete