HTML and CSS Reference
In-Depth Information
Next, you need to handle the popstate event so that when you navigate to a history entry, you can
generate the slide as per the history state information. This way, you can synchronize the current slide with
the URL being shown in the address bar. Listing 6-9 shows how the popstate event is handled.
Listing 6-9. Handling the popstate Event
$(document).ready(function () {
if (!Modernizr.history) {
alert("This browser doesn't support the HTML5 History API!");
}
else {
window.onpopstate = OnPopState;
}
...
});
function OnPopState(evt) {
$.Ajax({
type: "POST",
url: "/HTML5Home/GetImage",
data: '{ id : "' + evt.state.Id + '", direction : "" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (image) {
$("#id").val(image.Id);
$("#title").html(image.Title);
$("#desc").html(image.Description);
$("#img").src = image.ImageUrl;
},
error: OnError
})
}
Remember that the popstate event is raised for the window object, and hence you attach an event-
handler function OnPopState to the window. Notice how support for the History API is detected. The
OnPopState function makes an Ajax call to GetImage() using $.Ajax() . Recollect that while calling the
pushState() method, you specified the Image JSON object as the history state. The same Image JSON object
can be retrieved using the state property of the evt parameter. An ID of an image that is to be fetched is
then passed to the GetImage() method. Upon successful completion of the Ajax call, Image details such as
Title , Description , and ImageUrl are assigned to various <form> elements.
Finally, change the Index() action to take care of the optional image ID. Listing 6-10 shows the
modified version of Index() .
Listing 6-10. Index() Action Method, Which Now Takes Care of the Optional Image ID
public ActionResult Index(int id=0)
{
ImageDbEntities db = new ImageDbEntities();
IQueryable<Image> data = null;
if (id == 0)
{
data = (from item in db.Images
 
Search WWH ::




Custom Search