Geeks With Blogs

News ASP.net Forms Justin Hoffman
Justin Hoffman

Previously, I blogged about how to update the WebGrid in MVC 3 asynchronously.  This was when MVC 3 beta came out.  Later, I received a comment which confirmed that in fact my example no longer worked!!.  Hopefully, I can redeem myself with this post.

I took a slightly different approach in this example, using a partial view and reloading the grid with .ajax.

First, the ViewModel which is simple enough:

 

 using  System;
 using  System.Collections.Generic;
 using  System.Linq;
 using  System.Web;
 
 namespace  AsyncWebGrid.Models
 {
     public  class  ContactViewModel 
     {
         public  IEnumerable <Contact > Contacts { get ; set ; }
     }
 }

 

 
The Contact class:

 

 

 using  System;
 using  System.Collections.Generic;
 using  System.Linq;
 using  System.Web;
 
 namespace  AsyncWebGrid.Models
 {
     public  class  Contact 
     {
         /// <summary> 
         /// Gets or sets the id. 
         /// </summary> 
         /// <value> 
         /// The id. 
         /// </value> 
         public  int  Id { get ; set ; }
 
         /// <summary> 
         /// Gets or sets the first name. 
         /// </summary> 
         /// <value> 
         /// The first name. 
         /// </value> 
         public  string  FirstName { get ; set ; }
 
         /// <summary> 
         /// Gets or sets the last name. 
         /// </summary> 
         /// <value> 
         /// The last name. 
         /// </value> 
         public  string  LastName { get ; set ; }
 
         /// <summary> 
         /// Gets or sets the age. 
         /// </summary> 
         /// <value> 
         /// The age. 
         /// </value> 
         public  int  Age { get ; set ; }
     }
 }
 

The Controller has a couple different methods.  The important one is ReloadGrid.  This returns the partial view which actually has the WebGrid in it.  The ContactRepository is new'd up in the constructor for simplicity, obviously we would want to inject this normally.

 

 using  System;
 using  System.Collections.Generic;
 using  System.Linq;
 using  System.Web;
 using  System.Web.Helpers;
 using  System.Web.Mvc;
 using  AsyncWebGrid.Models;
 using  AsyncWebGrid.Repositories;
 
 namespace  AsyncWebGrid.Controllers
 {
     public  class  HomeController  : Controller 
     {
         private  readonly  IContactRepository  _contactRepository;
 
         public  HomeController()
         {
             _contactRepository = new  ContactRepository ();
         }
 
 
         /// <summary> 
         /// Indexes this instance. 
         /// </summary> 
         /// <returns></returns> 
         public  ActionResult  Index()
         {
            
             var  viewModel = new  ContactViewModel 
                                 {
                                     Contacts = this ._contactRepository.GetContacts(),
                                 };
 
 
             return  View(viewModel);
         }
 
         /// <summary> 
         /// Deletes the person. 
         /// </summary> 
         /// <param name="id">The id.</param> 
         /// <returns></returns> 
         [HttpPost ]
         public  ActionResult  DeletePerson(int  id)
         {
             this ._contactRepository.DeleteContact(id);
             return  null ;
         }
 
         /// <summary> 
         /// Reloads the grid. 
         /// </summary> 
         /// <returns></returns> 
         public  ActionResult  ReloadGrid()
         {
             return  PartialView("_Contacts" , this ._contactRepository.GetContacts());
 
         }
 
     }
 }
 
 

Finally the Views. First Index.cshtml

 

  @model   AsyncWebGrid.Models.ContactViewModel 
 
  @{  
     ViewBag.Title = "Index" ;
  }  
 
 <h2> Index</h2> 
 
  <div  id="grid"> 
          @  Html.Partial("_Contacts" , Model.Contacts)
  </div>
 

The PartialView _Contacts.cshtml, which is where everything happens along with the javascript function for reloading the grid:

  @model   IEnumerable <AsyncWebGrid.Models.Contact >
 
  @{          
     
     var  grid = new  WebGrid (source: Model,
                                     defaultSort: "FirstName" , 
                                     ajaxUpdateContainerId: "grid" ,
                                     rowsPerPage: 15);
   }  
 
            @  grid.GetHtml(
                   tableStyle: "grid" ,
                   headerStyle: "head" ,
                    alternatingRowStyle: "alt" ,
                   columns: grid.Columns(
 
                                             grid.Column(format: (item) => Ajax.ActionLink("Delete" , "DeletePerson" ,
                                                                         new  { id = item.Id },
                                                                         new  AjaxOptions  { HttpMethod = "POST" , OnSuccess= "reloadGrid" })),
                                                                         
                            grid.Column("Id" ),
                            grid.Column("FirstName" ),
                            grid.Column("LastName" ),
                            grid.Column("Age" )
                   )
           )
 

JS:

 function  reloadGrid() {
 
     $.ajax(
         { type: "GET" ,
             url: '/Home/ReloadGrid/' ,
             data: "{}" ,
             cache: false ,
             dataType: "html" ,
             success: function  (data)
             { $( ).html(data); } 
         })
 }
 

In my first attempts to correct this post one issue I kept encountering was that jquery.load would only reload the grid the first time it was called.  Each time after that nothing would happen.  I did some searching and came across this blog which helped me out with an alternative.

Posted on Friday, April 1, 2011 2:30 PM | Back to top


Comments on this post: MVC 3 Updating the Content of a WebGrid Async (Revisited)

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
After reload default paging does not seem to work, any idea?
Left by Rambo on Jun 13, 2011 10:25 AM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
@Rambo...I didn't really get in to paging in my example, but I don't see why that wouldn't continue to function as normal after reload. Can you post your View/JS code? I'll see if I can help
Left by Justin on Jun 13, 2011 9:12 PM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
The reason it doesn;t work is beacuse of the paging URL gets changed after refresh, very much similar to this post.

http://stackoverflow.com/questions/5931869/ajax-actionlink-partial-and-webgrid-issue

The grid gets loaded in the default Index action. But refresh happens through a seperate action method that just returns the partia view for the grid data.
Left by Rambo on Jun 22, 2011 7:30 AM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
Paging URL before refresh:
-------
2

After refresh
---------------
2

The action name is added to the action url with params
Left by Rambo on Jun 22, 2011 7:41 AM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
Sorry HTML messed up!

Before refresh

onclick="$('#grid2').load('/Secretary?gridPendingAssign_page=2&amp;__=634443430738116068 #grid2');" href="#">

After refresh

onclick="$('#grid2').load('/Secretary/PendingAssign?gridPendingAssign_page=2&amp;__=634443430989036068 #grid2');" href="#">
Left by Rambo on Jun 22, 2011 7:43 AM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
Any update on this? thanks in advance.
Left by Rambo on Jun 23, 2011 5:31 AM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
Rambo, did you check out the solution that was posted in the StackOverflow article you referenced? I assume that did not work for you? I will try to dig back into this when I can.
Left by Justin on Jun 23, 2011 10:31 AM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
Thanks Justin for the quick response.I can;t use solution outlined in StackOverflow because I have got three webgrids in my page. I can;t use the same method "Refresh" to load the data for three different grids.
Left by Rambo on Jun 24, 2011 6:28 AM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
Rambo, I think you could use the same method Refresh to reload each grid.
Consider the following:
You have three grids, grid1, grid2, grid3. The simplest way I can think of here is to create 3 "reloadGrid" functions and pass the grid name (or any indicator that will allow it to know which grid is in scope).
function reloadGrid()type: "GET" , url: '/Home/ReloadGrid/*Grid1*' ,
Or create a reload grid functio that takes arguments.
.
The method in the controller would accept that argument and thus be able to tell which partial view to return
Left by Justin on Jun 24, 2011 10:16 AM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
Thanks Justin. Infact I tried the same solution. As soon as I add the parameters to "Refresh" method the paging URLs get overwritten.
Left by Rambo on Jun 27, 2011 10:33 AM

# re: MVC 3 Updating the Content of a WebGrid Async (Revisited)
Requesting Gravatar...
So, there is no solution for this? WebGrid simply does not work when AJAX is being used to reload it?
Left by Eric on Jul 18, 2011 5:24 PM

Comments have been closed on this topic.
Copyright © Justin Hoffman | Powered by: GeeksWithBlogs.net