Wednesday, January 13, 2016

Ajax ActionLink - ASP.NET MVC

In this example I create an Ajax Action Link. Using the ActionLink load a partial view to the page.

1. In my view I create an ActionLink as

<div  id="latestReview">
    @Ajax.ActionLink("Get Latest Review", "LatestReview", new AjaxOptions
{
    UpdateTargetId = "latestReview",
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "GET",
    LoadingElementId = "progress"
})
</div >

also add another div for later use

<div id="progress">
    <img src="@Url.Content("~/Images/loading.gif")" />
</div >


In @Ajax.ActionLink()

  • The second parameter is the Action method which will be invoked on click
  • The third parameter specifies the ajax options


In the AjaxOption

  • The "UpdateTargetId" specifies the location in the DOM to display the result.
  • The "InsertionMode" provides the options such as Before, after or replace.
  • The "LoadingElementId" specifies the "progress" div to display until the view is partial view loaded

2. Next, in the controller create an Action method

In this example I omit the DB calls, instead create a dummy object of type BookReview. Note the return is a partial view


        public PartialViewResult LatestReview()
        {
            var modelTwo = new BookReview()
            {
                Name = "Samson",
                Rating = 7
            };
            Thread.Sleep(2000);
            return PartialView("_Review", modelTwo);
        }

a delay is created to show the "LoadingElementId" behaviour in the link

3. Create the partial view

@model MvcBookReview.Models.BookReview

<div class="review">
    <table class="rating">
        <tr class="ratinghead"><th>User</th><th>Rating</th></tr>
        <tr><td>@Model.Name</td><td>@Model.Rating</td></tr>
    </table>       
</div>

Note:
If you don't have the JQuery unobtrusive ajax library ("jquery.unobtrusive-ajax.min.js")in your solution, the ajax action link would not work properly. Add it to your solution through the Visual Studio Nuget Package Manager.

Result
The 3 stages: link, while processing action, result


When you have a look at the link through the browser's developer tool you will see something like this


No comments:

Post a Comment