• Home
  • New Entries
  • Popular Entries
  • Submit a Story
  • About

Asp.net Mvc Jquery Progressbar ...

In this tutorial you will know how to process a long running task asynchronously using ASP.Net MVC along with JQuery to update a progress bar on the view via Ajax.

- Create a class that will manage the long running task, the dictionary is used to allow for multiple users firing off individual long running tasks.

   1. using System.Collections.Generic;
   2. using System.Linq;
   3. using System.Threading;
   4. namespace AjaxProgressBarExample
   5. {
   6. 
   7.     /// <summary>
   8.     /// Long Running Test Class.
   9.     /// </summary>
  10.     public class MyLongRunningClass
  11.     {
  12. 
  13.         private static object syncRoot = new object();
  14. 
  15.         /// <summary>
  16.         /// Gets or sets the process status.
  17.         /// </summary>
  18.         /// <value>The process status.</value>
  19.         private static IDictionary<string, int> ProcessStatus { get; set; }
  20. 
  21.         /// <summary>
  22.         /// Initializes a new instance of the <see cref="MyLongRunningClass"/> class.
  23.         /// </summary>
  24.         public MyLongRunningClass()
  25.         {
  26.             if (ProcessStatus == null)
  27.             {
  28.                 ProcessStatus = new Dictionary<string, int>();
  29.             }
  30.         }
  31. 
  32.         /// <summary>
  33.         /// Processes the long running action.
  34.         /// </summary>
  35.         /// <param name="id">The id.</param>
  36.         public string ProcessLongRunningAction(string id)
  37.         {
  38.             for (int i = 1; i <= 100; i++)
  39.             {
  40.                 Thread.Sleep(100);
  41.                 lock (syncRoot)
  42.                 {
  43.                     ProcessStatus[id] = i;
  44.                 }
  45.             }
  46.             return id;
  47.         }
  48. 
  49.         /// <summary>
  50.         /// Adds the specified id.
  51.         /// </summary>
  52.         /// <param name="id">The id.</param>
  53.         public void Add(string id)
  54.         {
  55.             lock (syncRoot)
  56.             {
  57.                 ProcessStatus.Add(id, 0);
  58.             }
  59.         }
  60. 
  61.         /// <summary>
  62.         /// Removes the specified id.
  63.         /// </summary>
  64.         /// <param name="id">The id.</param>
  65.         public void Remove(string id)
  66.         {
  67.             lock (syncRoot)
  68.             {
  69.                 ProcessStatus.Remove(id);
  70.             }
  71.         }
  72. 
  73.         /// <summary>
  74.         /// Gets the status.
  75.         /// </summary>
  76.         /// <param name="id">The id.</param>
  77.         public int GetStatus(string id)
  78.         {
  79.             lock (syncRoot)
  80.             {
  81.                 if (ProcessStatus.Keys.Count(x => x == id) == 1)
  82.                 {
  83.                     return ProcessStatus[id];
  84.                 }
  85.                 else
  86.                 {
  87.                     return 100;
  88.                 }
  89.             }
  90.         }
  91.     }
  92. }

The GetCurrentProgress(string id) content result method sole purpose is to return the current status of the long running process by looking it up in the dictionary (it’s a bit hacky but this is only for demo purposes).

   1. using System;
   2. using System.Linq;
   3. using System.Web.Mvc;
   4. 
   5. namespace AjaxProgressBarExample.Controllers
   6. {
   7.     /// <summary>
   8.     /// Home Controller.
   9.     /// </summary>
  10.     [HandleError]
  11.     public class HomeController : Controller
  12.     {
  13.         /// <summary>
  14.         /// Index Action.
  15.         /// </summary>
  16.         public ActionResult Index()
  17.         {
  18.             ViewData["Message"] = "Ajax Progress Bar Example";
  19.             return View();
  20.         }
  21. 
  22.         delegate string ProcessTask(string id);
  23.         MyLongRunningClass longRunningClass = new MyLongRunningClass();
  24. 
  25.         /// <summary>
  26.         /// Starts the long running process.
  27.         /// </summary>
  28.         /// <param name="id">The id.</param>
  29.         public void StartLongRunningProcess(string id)
  30.         {
  31.             longRunningClass.Add(id);           
  32.             ProcessTask processTask = new ProcessTask(longRunningClass.ProcessLongRunningAction);
  33.             processTask.BeginInvoke(id, new AsyncCallback(EndLongRunningProcess), processTask);
  34.         }
  35. 
  36.         /// <summary>
  37.         /// Ends the long running process.
  38.         /// </summary>
  39.         /// <param name="result">The result.</param>
  40.         public void EndLongRunningProcess(IAsyncResult result)
  41.         {
  42.             ProcessTask processTask = (ProcessTask)result.AsyncState;
  43.             string id = processTask.EndInvoke(result);
  44.             longRunningClass.Remove(id);
  45.         }
  46. 
  47.         /// <summary>
  48.         /// Gets the current progress.
  49.         /// </summary>
  50.         /// <param name="id">The id.</param>
  51.         public ContentResult GetCurrentProgress(string id)
  52.         {
  53.             this.ControllerContext.HttpContext.Response.AddHeader("cache-control", "no-cache");
  54.             var currentProgress = longRunningClass.GetStatus(id).ToString();
  55.             return Content(currentProgress);
  56.         }
  57.     }
  58. }

The next thing to do is create the view using the index view itself, The getStatus method uses ajax to call the GetCurrentProcess content result method on the controller every 100 milliseconds.



   1. <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
   2. 
   3. <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
   4.     Home Page
   5. </asp:Content>
   6. <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
   7.     <h2>
   8.         <%= Html.Encode(ViewData["Message"]) %></h2>
   9.     <div>
  10.         <a href="#" id="startProcess">Start Long Running Process</a>
  11.     </div>
  12.     <br />
  13.     <div id="statusBorder">
  14.         <div id="statusFill">
  15.         </div>
  16.     </div>
  17. 
  18.     <script type="text/javascript">
  19. 
  20.         var uniqueId = <%= Guid.NewGuid().ToString() %>;
  21. 
  22.         $(document).ready(function(event) {
  23.             $(#startProcess).click(function() {
  24.                 $.post("Home/StartLongRunningProcess", { id: uniqueId }, function() {
  25.                     $(#statusBorder).show();
  26.                     getStatus();
  27.                 });
  28.                 event.preventDefault;
  29.             });
  30.         });
  31. 
  32.         function getStatus() {
  33.             var url = Home/GetCurrentProgress/ + uniqueId;
  34.             $.get(url, function(data) {
  35.                 if (data != "100") {
  36.                     $(#status).html(data);
  37.                     $(#statusFill).width(data);
  38.                     window.setTimeout("getStatus()", 100);
  39.                 }
  40.                 else {
  41.                     $(#status).html("Done");
  42.                     $(#statusBorder).hide();
  43.                     alert("The Long process has finished");
  44.                 };
  45.             });
  46.         }
  47.    
  48.     </script>
  49. 
  50. </asp:Content>

Css for styling the progress bar:

   1. #statusBorder
   2. {
   3.     position:relative;
   4.     height:5px;
   5.     width:100px;
   6.     border:solid 1px gray;
   7.     display:none;
   8. }
   9. #statusFill
  10. {
  11.     position:absolute;
  12.     top:0;
  13.     left:0;
  14.     width:0px;
  15.     background-color:Blue;
  16.     height:5px;
  17. }

 Original Source:
http://weblogs.asp.net/seanmcalinden/archive/2009/11/15/asynchronous-processing-in-asp-net-mvc-with-ajax-progress-bar.aspx

AddThis Social Bookmark Button

Posted at 11:46:11 am | Permalink | Posted in jQuery  

Related Stuff

  • MooV: Using cutting edge Video phones and Software Video Phones - coupling all that with VoIP and empowering the disabled.

  • Moo Telecom: VoIP communications made easy - Ring anyway with the fun and ease of using a normal phone

  • TagR:Mobile Social Network with Real Time Locations Based services, and Ambience Intelligence, VoiP, IM, Skype, Googletalk, Mapping, Flickr, Events, Calendaring, Scheduling, SecondLife Support

  • ClearSMS : ClearSMS is a Web-based application that lets you send bulk SMS messages to your customers, contacts, or just about anyone.

  • Jajah:jah is a VoIP (Voice over IP) provider, founded by Austrians Roman Scharf and Daniel Mattes in 2005[1]. The Jajah headquarters are located in Mountain View, CA, USA, and Luxembourg. Jajah maintains a development centre in Israel.

  • Skype: It’s free to download and free to call other people on Skype. Skype the number one voice over ip software

  • PrivatePhone: a free local phone number with voicemail and messages you can check online or from any phone.

Top Stuff

e-messenger

MSN Web Messenger

eBuddy

ASP.NET Ajax CalendarExtender and Validation

AIM Express

Ajax Tools for ASP.NET Developers



About Ajaxlines

Ajaxlines is a project focused on providing its audience with a database of most of Ajax related articles, resources, tutorials and services from around the world.

Its purpose is to showcase the power of Ajax and to act as a portal to the Ajax development community.


Search


Topics

  • .Net (176)
  • Ajax (112)
  • Ajax Games (10)
  • Articles (95)
  • Bookmarking (35)
  • Calendar (21)
  • Chat (45)
  • ColdFusion (3)
  • CSS (84)
  • Email (23)
  • Facebook (84)
  • Flash (20)
  • Google (54)
  • Html (29)
  • Image (12)
  • International Calls & VOIP (7)
  • Java (58)
  • Javascript (280)
  • jQuery (200)
  • JSON (75)
  • Perl (2)
  • PHP (172)
  • Presentation (19)
  • Python (3)
  • Resources (2)
  • RSS (8)
  • Ruby (32)
  • Storage (4)
  • Toolkits (103)
  • Tutorials (227)
  • UI (11)
  • Utilities (174)
  • Web2.0 (18)
  • XmlHttpRequest (29)
  • YUI (13)

© 2006 www.ajaxlines.com. All Rights Reserved. Powered by IRange