Showing Progress of a ASP.NET MVC PartialView

Thursday, December 17, 2009 0 comments

What you’ll need for this recipe:

  1. Some long running GET that you really don’t want the rest of the page load to wait for.
  2. New ActionResult in a Controller that returns a PartialView.
  3. ViewUserControl that will display the results of your long running GET.
  4. jQuery and a javascript snippet that will go call your action and load your result.

Step 1 – Action Result

   1: public ActionResult CreateData(int item) 
   2: { 
   3:     // Go to your Model/API/Service and get the long running stuff
   4:     List<String> LargeList = Model.GoGetList(item);
   5:     
   6:     // You can either add it to the ViewData or return it.. 
   7:     // Do what you like
   8:     ViewData.Add("ElementIdS", group.ElementIds); 
   9:     
  10:     // Go return your control.. 
  11:     //it's named the same as you *.ascx file
  12:     return PartialView("UserControl"); 
  13: }

Step 2 – ViewUserControl

Go create you *.ascx file.  This one could be call UserControl.ascx.  Add some HTML to render your long running piece of data.

Step 3 – jQuery

   1: <script language="javascript" type="text/javascript" >
   2:     // just run at page load time
   3:     jQuery(document).ready(function() {
   4:         // this is the name of the empty div
   5:         // that you'll load with your PartialView and data
   6:         var targetDiv = $("#divTarget");
   7:         // this is just like the old UpdatePanel Progress stuff
   8:         var ajaxLoading = '<img id="ajax-loading" src="<%= Url.Content("~/Content/images/loading.gif") %>" height="20px" width="20px" />';
   9:         // go call your Controllers action called Create Data
  10:         var action = '<%=Url.Action("CreateData", "Home", new RouteValueDictionary(new { item = Model.Id }))%>'
  11:         // for now we are loading.. it's not done yet
  12:         $(targetDiv).html(" " + ajaxLoading + " Loading... ");
  13:         // lets go get our ActionResult.. with get
  14:         // we just pass the url and name the result.. "result"
  15:         $.get(action, null, function(result) {
  16:             //  pretty fade
  17:             $(targetDiv).fadeIn('slow');
  18:             // make the html in the target div the result of the PartialView
  19:             $(targetDiv).html(result);
  20:         });
  21:     });
  22: </script>

Step 4 – Hook it up and run

Run.  It works.

 
Copyright © Aaron Stanley King