[ASP.NET MVC] Unobtrusive Ajax [2] – AjaxOptions

In the previous post, I showed how you can use AJAX using “Unobtrusive Ajax”. Without a single line of JavaScript, it works like a magic.

In this second post of the series, I will delve into the inner workings of the feature.

1. What is Happening Here?

Let’s look at the previous example again.

@using (Ajax.BeginForm("ProductDetail", ajaxOpts))
{
  <div>
  Type the product Id: @Html.TextBox("id")
  </div>
  <div>
  To see the detailed information of the product:
  <input type="submit" value= "Click Me" />
  </div>
}

When you examine the HTML output, you can see how the form element is created.

<form action="/Ajax/ProductDetail" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#productDetail" id="form0" method="post">
...
</form>

The “jquery.unobtrusive-ajax.js” library makes use of custom attributes of the form element.

  • The unobtrusive ajax library scans the form whose “data-ajax” attribute is true.
  • Other attributes “data-ajax-xxx” can be configured by an “AjaxOptions” object

 

2. Displaying the Progress Bar

One of the problems of Ajax loading is lack of visual indication of the action.

You need to set the following 2 properties:

  • LoadingElementId 
  • LoadingElementDuration: duration for animation in milliseconds
@{
  ViewBag.Title = "ViewProduct";
  AjaxOptions ajaxOpts = new AjaxOptions {
    UpdateTargetId = "productDetail",
    LoadingElementId = "loadDiv",
    LoadingElementDuration = 2000 };
}

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

You might need to add the “Sleep()” to the controller action for a better testing.

 

3. Confirming the Request

Suppose you want to send a “Delete Product” request. It is better to ask a user to confirm the action.

  • Confirm: a message that will be used to prompt the user before an Ajax request

You can cancel the quest by clicking the “Cancel” button.

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