somemvcperson
somemvcperson

Reputation: 1253

Clientside URL Routing

Looking at turning my ASP MVC app into pure JS/Html however its not just a 1 page app, it has a couple of pages, but each one has alot of ajax and events.

Anyway currently my urls on ASP MVC are like:

/login
/admin/{action}/{adminId}
/posts/{posterId}
/picture/{pictureId}

So that is all nice and simple and easy to see what you are doing in the url, you also get correct back button behaviour. So trying to adopt this sort of thing to a pure JS/Html approach seems to bit either very tough or impossible. I dont need an exact match but I was hoping to do something like:

http://localhost/myapp/posts/10

Then that would somehow be able to route the actual request to http://localhost/myapp/posts.html with the variable exposed. Now I am pretty sure this is impossible as when the above is entered into the browser it is going to attempt to look in a directory called posts and look for 10, which wont exist.

Now I have seen Crossroads and LeviRoutes and a few other similar technologies, however they seem to rely upon the hashbang method, which some people like others hate. Is there any way around this? If not can anyone point to any good tutorials on how to use these frameworks, as each seems fairly light on documentation.

Upvotes: 2

Views: 1979

Answers (2)

Cat Chen
Cat Chen

Reputation: 2415

There's no workaround for not using hash. HTML5 History API isn't available on IE and Opera yet. If your application is targeting very specific platform, then you can use History API instead of hash. However, History API is inconsistent across browsers. You can read it here: http://www.battlehorse.net/page/2011/02/12/html5history.htm

If you choose to use History API, it would be easy. You can use whatever routing strategy you want in ASP.NET MVC, then just match this strategy in JavaScript. You can read more about History API here: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

If you choose to use hash, you need to do make some requests into AJAX requests:

  • Determine if a request is done via AJAX:
    • if GET/posts/{action}/{id} is by AJAX, serve the original content
    • if it's not by AJAX, redirect the user to /#!/posts/{action}/{id}.
  • Handle client side hash by requesting for the right content:
    • When the hash is changed to #!/posts/{action}/{id}, GET /posts/{action}/{id} via AJAX and replace the content with the new one from the server.
  • Intercept form.onsubmit event:
    • Whenever a form is trying to submit to /posts/{action}/{id}, cancel it and use AJAX to post and then replace the content with the new one from the server.

Now your app should work like a one page app.

Upvotes: 1

Martin Jespersen
Martin Jespersen

Reputation: 26183

There is no real way around hashbangs if you wish to keep it clientside and cross browser compatible.

Upvotes: 0

Related Questions