In this article i'm gonna show you how i do when i have to update some content with AJAX and i have to change the URL.
First, let's see an example to understand it better.
If the user is reading a News with Id 1 and he clicked on another News with Id 2, if we update the content with AJAX the user is now reading the News Id 2 but the URL remains the same, for example: http://localhost/News/Read/1
Now let's see another example from Facebook. If i'm reading my profile and i click on Photos, Facebook updates it with AJAX and the URL switch to: http://www.facebook.com/guilhermegeek#!/guilhermegeek?sk=photos
If we enter on that URL, it's mapped to: http://www.facebook.com/guilhermegeek?sk=photos
The trick here is the parameters that we use after the #!. Those parameters are never sent to the server side, so we handle them on the client side (javascript).In the example of Facebook, he receives my profile name (guilhermegeek) and the action is to read photos.
A few time ago i've written an article in my Portuguese blog explaining how to use an alternative to clients with javascript disabled. Like this:
<a onclick="javascript:ReadNews(id);" href="#!News/Read/@id/">Title</a>
When the user enter the link of that news, my function Read(); fills the News in the page. Then, i add the #!News/Read/@id/ to my URL. It's gonna stay something like this:
http://localhost/News/Read/1#!News/Read/2
As i explained before, the News that the user is reading has the Id 2.The next step is to use javascript to check if the URL that the user typed has other News Id, because if we enter on the above URL our controller will get the Id 1 (everything after to the # isn't sent to the server side).
$(document).ready(function () {
var h = window.location.hash;
if (h != null) {
var parts = window.location.href.split('#!');
if (parts.length > 1) {
window.location.replace("http://localhost/" + parts[1]);
}
}
});
It's pretty simple. I'm cutting everything after the #!, then i redirect the user to a new page. So, it's gonna stay:http://localhost/News/Read/2