Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load view without reloading the layout in MVC 4?

I am working with ASP.NET MVC 4. I've a slightly heavier "navigation menu" and "header" which common for all pages.

I've created all the menu and header stuff in a layout, but in each navigation, browser reloading the menu. Is there any possible way to prevent reloading of layout page?

I'm using _ViewStart.cshtml to bind the views with the layout.

like image 349
Vinu Avatar asked Aug 22 '13 05:08

Vinu


Video Answer


3 Answers

Assuming this will be your menu HTML rendered

   <ul class="menu">
      <li><a href="/about/index">About</a></li>
      <li><a href="/contact/index">Contact</a></li>
   </ul>
   <div id="page-content">
   </div>

Your view pages will be created as partial views in the below structure

About/index.cshtml
Contact/index.cshtml

Note: MVC partial views will not have <html> or <head> or <body>, it will just have the content, similar to user control in ASP.Net. You cannot use @section in partial views

Now all you need is load this partial content using ajax and place it in the main placeholder div for a page content using javascript

$(document).ready(function(){
$("ul.menu a").click(function(e){
  e.preventDefault(); // prevent default link button redirect behaviour     
  var url=$(this).attr("href");
  $('#page-content').load(url);
 });
});

Hope this will help you!

like image 192
Murali Murugesan Avatar answered Oct 10 '22 09:10

Murali Murugesan


You should try out caching the navigation menu and header if they are common to all the pages.

If your resultant view is made up of

  1. header
  2. navigation
  3. menu content

and you could use a layout

@Html.RenderAction("header")
@Html.RenderAction("navigation")
@Render.Body()

where the "header" and "navigation" actions are cached heavily.

@Haacked mentioned this awesome blog post here http://haacked.com/archive/2009/05/11/donut-hole-caching.aspx

This approach cleanly separates out your concern for header and navigation. And you can focus on the actual content to be displayed by the Action currently called.

Hope this helps

Note : This answer super simplified and you would have to take into consideration dynamic parameters and stuff while performing caching if your navigation based upon roles/permissions of users accessing the pages.

like image 20
frictionlesspulley Avatar answered Oct 10 '22 09:10

frictionlesspulley


Best way is to return a partial view from the controller:

return PartialView();

You could also override the _layout in the layout of the partial view being loaded by adding to the top:

@{
    Layout = null;
}
like image 1
Stu Avatar answered Oct 10 '22 10:10

Stu