Wednesday, February 23, 2011

Ajax deep linking using javascript in ASP.NET page

I recently created an asp.net page with deep-linking feature by using javascript.
The original page is designed to have ajax like feature. It was divided into two columns: left tree menu and the right column is the main content. When the user click the a node in the tree, the content will be changed in the right column. Without deep linking, the user will not be able to go to a specific content page. However, the browser URL can't be modified by adding a query string parameter, e.g. "content.aspx?id=33". After some googling, I found out that a browser link can be modified by adding a "hash code", e.g. "content.aspx#id=33".

javascript code to add a hash code to the current URL:
function AddHashToLink(hashCode) {
location.hash = hashCode;
}

Another issue came out when I tried to get the hashcode "#id=33" from the server side. Browser just remove the hash code and pass the URL as "content.aspx" instead of "content.aspx#id=33" to the server side. The only place to see "#id=33" is from the browser. So I decided to use javascript again to read this hash code and pass it to a frame after the page "content.aspx" is loaded.

JQuery ready function:
$(document).ready(function () {
SetContent();
});

function SetContent() {
var theFrame = $("#content", document.body);
if (document.URL.toLowerCase().indexOf("id=") !== -1) {
var clickedHREF = document.URL.toLowerCase();
var clickedSubInd = clickedHREF.split("id=");
theFrame.attr('src', "anotherContent.aspx?id=" + clickedSubInd[1]);
}
else {
theFrame.attr('src', "anotherContent.aspx");
}
}

This way, when the user request to go to link "content.aspx#id=33", the page "content.aspx" will be loaded first. Then the jquery ready function will call setContent() and set the link "anotherContent.aspx?id=33" to the frame with id "content". This way, the user will see the page of "content.aspx#id=33" instead of "content.aspx".

Some javascript function to know:
"document.URL" to get the current URL in the browser

"theFrame.attr('src', "anotherContent.aspx"); " is a jquery function to set the SRC atribute of a frame.

No comments:

Post a Comment