Reputation: 183
I am working on a project and in order to not have the Layout view being reloaded with every page change, I decided to change my views to partial views. In order to load the views when a user clicks on one of the menu items in the navigation menu I am now using jquery ajax like the following:-
$("ul.metismenu a:not(.subMenuParent)").unbind().click(function (e) {
e.preventDefault();
var url = $(this).attr("href");
window.history.pushState("", "", url);
$.ajax({
url: url,
dataType: 'html',
success: function (data) {
$('#page-content').html(data);
}
});
});
The element page-content resides in the Layout view. It is working fine, however the issue I am encountering now is that when i try to access the View directly say i go /Dashboard directly in the browser I will get just the partial view, without the Layout page. Anyone got some ideas how I can solve this please? Thank you in advance for any advice.
Upvotes: 0
Views: 481
Reputation: 183
I was able to fix the issue by first checking if the request coming is an ajax request or not. Then depending on the type of request i set the Layout view. This is a sample code from an action:-
public ActionResult Index()
{
if (!Request.IsAjaxRequest())
{
ViewBag.Layout = "~/Views/Shared/_Layout.cshtml";
}
return PartialView();
}
And in the partial view i set the following:-
@{
Layout = ViewBag.Layout;
}
Hope this helps someone who might encounter the same issue.
Upvotes: 0
Reputation: 304
You can have different layout set from different controller actions by using a variable. Even a ViewBag would suffice. For the action Dashboard , you can set the ViewBag.Layout (say) to the Layout html and for the partial view you can set ViewBag.Layout to empty. THen use this variable in the html page. So, the right layout will be picked up depending on the action we are calling.
Upvotes: 1
Reputation: 440
your url call MVC Action
, make your return ActionResult
: PartialView()
Upvotes: 0