Tuesday, 15 November 2011

MVC Ajax with Partial Views

What we want:   A partial to be loaded on "page load" and to be updated on an action.  If you remember Jim's lecture the contents of the "UpdateTargetId" are replace with the new Ajax command. So we need something to that will fill the html element at initial load.   I had some initial issues with this as the Ajax.Action link did not seem to fire the Get for the action so I had to change the ActionLink to a post and insert an dummy post action [HttpPost] in the control and it all worked after this.  I use   Html.RenderAction to load the initial partial. Note this will Render the contents of a Controller Action which in this case returns a partial view. Below is a simple GetTime Example then  THE GREEN WILL GET REPLACED BY THE AJAX CALL Html :

  @Ajax.ActionLink("GetTime", "GetTime", "Home", new { name = "anything"},  new AjaxOptions { UpdateTargetId = "currenttime" }) 
     @{ Html.RenderAction("GetTime", "Home"); }


  public ActionResult GetTime(string name)
   // string name  : THIS IS NOT USED DUMMY
   return GetTime();     

public ActionResult  GetTime()        
      string model = DateTime.Now;
      return PartialView("_ShowTime", model);

Note on Html.RenderAction

THIS WORKS  IN A VIEW   @{ Html.RenderAction("GetTime", "Home"); }
THIS DOES NOT WORK IN A VIEW   @Html.RenderAction("GetTime", "Home"); 

Model Enumeration with Ajax  and Partial Views

If we expand the above example where you want to update a partial with a List which will give multiple Ajax calls on the same rendered page (remember this creates JavaScript when rendered and we have to bear this in mind).  So we will need to ensure that Html element id are unique for each item in our View or things will start to get interesting.  So the View code below will ensure that if we hit a link we will update the correct item within a page. 

Html:@foreach (var item in Model)
{     string elementId =  "GetTime" + item.id;      
       @Ajax.ActionLink("GetTime", "GetTime", "Home", new { name = model.id},  new AjaxOptions {                                  
                                        UpdateTargetId = elementId })   @elementId ">

     @{ Html.RenderAction("GetTime", "Home",  
new { name = model.id}); }

Note:  In the above example we are always passing a parameter to the Controller Action so we load the correct data for the model. Code:

 public ActionResult GetTime(string id)
     List model = GetmyStuff.Get(id);   
   return PartialView("_ShowStuff", model);

No comments:

Post a Comment

Comments are welcome, but are moderated and may take a wee while before shown.