Search code examples
ajaxasp.net-mvcasp.net-mvc-4asp.net-mvc-5unobtrusive-javascript

Should a Menu load a Views or a Partial Views in MVC 5?


To keep it simple imagine a site with a menu with three buttons at the left and a Content area to the right. The buttons loads content to the Content area.

When a button is clicked I want:

1) The URL to change accordingly. Meaning that if the buttons are "Foo", "Bar" and "Baz". I want the URL to be something like "http://localhost/mySite/Baz/ShowBazs, when the 3rd button is clicked.

2) The button should be highlighted with a CSS class. (with a little jquery before making the AJAX request)

3) (Only ?) the Content area should loaded


Loading a View

  1. Ok
  2. Not Ok. Menu gets reloade back to scratch
  3. Semi Ok. Menu gets reloade back to scratch. Content area loads fine into @RenderBody()

Loading a Partial View

1) Not Ok. Notthing happens to the URL

2) Ok. Menu is not reloade

3) Ok. Only Content area is loade.


I know there is not a single answer to design all websites. Just feels like I am missing something good here.

What would the best solution be here in your opinion and why?

At the moment I only use Partial views in the Content area. The menu is fine, and the Content only gets loaded and its really fine. BUT the URL is stayes the same and it feels wrong not to use Views at all.

My best idea is to rewrite the site to use Views and then make the view responsible for setting the highlighted button.


Solution

  • The only possible way to achieve all of your design requirements is via the History API in HTML 5 (in other words, it will only work in modern browsers: IE 10+ and virtually every other browser known to man). There's a polyfill for supporting IE 9 and below: History.js. However, it uses URL fragments (#foo) in those browsers, so the URL structure won't be exactly the same. It's a good script to include regardless, though, since the History API is implemented somewhat differently among browsers that do support it, and the polyfill helps to keep everything on the same footing.