Sunday, March 27, 2011

What is the best way to implement an AJAX main menu?

I'm building a site using ASP.NET MVC with lots of jQuery and AJAX stuff, and I'd like the main menu to work with AJAX as more or less the rest of the site does.

In an ideal scenario, I would like my main menu to 1) load the main content with AJAX if the user has activated javascript 2) change the url in the address bar (to enable link copy-pasting) 3) have my code in only one place, meaning that I don't want to have the same markup in an .aspx View and an .ascx PartialView.

Number 1) I have no problems with. However, I have no idea how I do to accomplish number 2) without a reload of the page. Any ideas?

I realize that the third issue could be solved by creating a View that renders each PartialView, but is there no nicer way around that? Some way to "wrap" the PartialView in the site Master or something at the Controller, before returning it to the client?

From stackoverflow
  • For #2: You can add a #hash to the end of the url: example in your menu:

    <a href="#helppage" onclick="opento('helppage')">Help Page</a>
    

    And then in your body on load:

    if(document.location.hash) { opento(document.location.hash); }
    

    For #3 I don't know ASP. Sorry.

    Tomas Lycken : Well, as I'm using ASP.NET MVC, all my urls will look like example.com/Home/About or example.com/Products/List - in other words, they need to actually point to different locations. Do you know any way to change the address bar's actual location, without loading the new page?
    Isaac Waller : There are libraries that do this and create urls like: example.com/#/Home/About using the technique I described above. Maybe if this is sufficient. If worst comes to worst, you could just create a giant Iframe that takes up the whole page, but uses my technique to add a hash to the main url. Isaac
  • I'm inclined to agree with Rob (though I won't vote you down ;)). JavaScript techniques like Ajax shouldn't be core to your site without good reason. I'd recommend searching Google for terms such as 'progressive enhancement' and 'unobtrusive javascript'.

    Build a nice RESTful site and then enhance with JavaScript and Ajax in places where it enhances the user experience to a significant degree.

  • Though I agree with some of the other comments about not loading content via AJAX for the sake of it, #2 in your list is a common problem that often crops up when dealing with AJAX and is worth answering.

    The only way to change the URL without the browser reloading is by adding a # to the end . Example:

    http://www.yoursite.com/Content/About/#some-identifier
    

    There is no other way. You can look at sites like Facebook and Google Mail/Reader to see an example of this implemented.

    Hope it helps...

0 comments:

Post a Comment