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.
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!
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
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With