[ASP.NET MVC] Unobtrusive Ajax [3] – Ajax Links

So far, we have used Unobtrusive Ajax with a form and a submit button. What if you want a link that acts asynchronously?

1. Ajax Helper Class

Do you know what “Ajax” refers to when you use the “@Ajax.BeginForm()”.

It is defined in the “WebViewPage<T>” class.

public abstract class WebViewPage<TModel> : WebViewPage
{
  public AjaxHelper Ajax { get; set; }
  public HtmlHelper Html { get; set; }
}

 

2. ActionLink Methods

The “System.Web.Mvc.AjaxHelper” class provides the “ActionLink” method to return an anchor element for Ajax request. There are many overloaded versions but generally you need to provide the following information:

  • string linkText
  • string actionName
  • string controllerName
  • Object routeValues
  • AjaxOptions ajaxOptions
  • Object htmlAttributes
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, AjaxOptions ajaxOptions);

public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, Object routeValues, AjaxOptions ajaxOptions, Object htmlAttributes);

 

3. Creating the Ajax Links

<div id="loadDiv" style="display:none; color:Red">Loading...</div>

@foreach (int i in Enumerable.Range(1, 10)) {
  <div style="margin-right:10px;">
  @Ajax.ActionLink(
    String.Format("Product {0}", i), // link text
    "ProductDetail", // action name
    new { id = i }, // route values
    new AjaxOptions {
      UpdateTargetId = "productDetail",
      LoadingElementId = "loadDiv" }
    )
  </div>
}

<div id="productDetail">
</div>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s