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.
You can download the complete source code or you can follow step by step discussion below. The sample code is developed in Microsoft Visual Studio 2013 Ultimate.
Let's begin now:
- Create new MVC web project and name it "ButtonLoader".
- Download the Ladda plugin and incorporate its related JavaScript & CSS files into the project.
- Create new controller under "Controller" folder and name it "LoaderController.cs".
- 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
- });
- }
- }
- }
- Create new file "LoaderViewModels.cs" under "Models" folder and place the 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.
- Now, open "LoaderController.cs" file under "Controller" folder and replace it with the following code:
-
-
-
-
-
-
- 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;
-
-
-
- public class LoaderController: Controller
- {
- #region Index view method.#region Get: /Loader/Index
- method.
-
-
-
-
- public ActionResult Index()
- {
- try
- {}
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
- return this.View();
- }#endregion# region POST: /Loader/Index
-
-
-
-
-
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult Index(LoaderViewModel model)
- {
- try
- {
-
- if (ModelState.IsValid)
- {
-
- Thread.Sleep(5000);
-
- return this.Json(new
- {
- EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text
- });
- }
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
- Thread.Sleep(5000);
-
- 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.
- Now, in "Views->Loader" folder create a new page called "Index.cshtml" and place the 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.
- Under "Scripts" folder, create a new script called "custom-loader.js" and place the 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");
-
- 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)
- {
-
- onLoaderSuccess(result);
- },
- error: function(jqXHR, textStatus, errorThrown)
- {
-
- alert("fail");
-
- Ladda.stopAll();
- }
- });
- });
- });
- var onLoaderSuccess = function(result)
- {
- if (result.EnableError)
- {
-
- $('#ModalTitleId').html("");
- $('#ModalContentId').html("");
-
- $('#ModalTitleId').append(result.ErrorTitle);
- $('#ModalContentId').append(result.ErrorMsg);
-
- $('#ModalMsgBoxId').modal(
- {
- backdrop: 'static',
- keyboard: false
- });
- }
- else if (result.EnableSuccess)
- {
-
- $('#ModalTitleId').html("");
- $('#ModalContentId').html("");
-
- $('#ModalTitleId').append(result.SuccessTitle);
- $('#ModalContentId').append(result.SuccessMsg);
-
- $('#ModalMsgBoxId').modal(
- {
- backdrop: 'static',
- keyboard: false
- });
-
- $('#LoaderformId').get(0).reset();
- }
-
- Ladda.stopAll();
- }
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.
- 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:
- Now, execute the application and you can see the following:
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