HTML and CSS Reference
In-Depth Information
clearly, let's convert the Slide Show application developed previously into an Ajax-driven application so
that slides are loaded using the jQuery
$.Ajax()
method without refreshing the entire page.
The Ajax version of the Slide Show application consists of a controller named
AjaxHomeController
that
contains the
Index()
action method, as shown in Listing 6-3.
Listing 6-3.
Index()
Action Method of
AjaxHomeController
public ActionResult Index()
{
ImageDbEntities db = new ImageDbEntities();
IQueryable<Image> data = null;
...
return View(data.SingleOrDefault());
}
This time, the
Index()
action method doesn't accept an image ID as a parameter because
Index()
is
invoked only once when the index view is rendered initially. After that, various slides are fetched via Ajax
calls. The
Index()
action method simply fetches the first image from the
Images
table and passes it to the
index view.
Now the Previous and Next buttons don't submit the form to the server. Instead, clicking these buttons
triggers Ajax calls to the server to fetch and display slides.
To display the previous or next slide, you need to handle the
click
event handlers of the Previous and
Next buttons. These event handlers are shown in Listing 6-4.
Listing 6-4.
Client-Side
click
Event Handlers of the Previous and Next Buttons
$("#prev").click(function () {
$.Ajax({
type: "POST",
url: "/AjaxHome/GetImage",
data:'{ id : "' + $("#id").val() + '", direction : "P"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
})
});
$("#next").click(function () {
$.Ajax({
type: "POST",
url: "/AjaxHome/GetImage",
data: '{ id : "' + $("#id").val() + '", direction : "N"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
})
});
These
click
event handlers of the Previous and Next buttons use the jQuery
$.Ajax()
method to
invoke the
GetImage()
action method. The
GetImage()
method expects two parameters: the ID of the