Reputation: 6060
Is there a way to determine if a view is rendering as a partial?
I'm hoping to extend the reuse of a partial that I'm writing by catching this...and if necessary assigning the appropriate layout to the View.
At the moment I'm just rendering it in a div, but I could also see us using it as a modal and possible it's own page.
(the modal shouldn't require any change so no worries there)
EDIT: To clear up what I'm asking.
I'm wondering if there is anyway to determine the difference between a view being rendered by...
/path/to/controller
and
Html.Partial("/path/to/view.cshtml")
Upvotes: 2
Views: 5211
Reputation: 2923
Not sure if this is exactly what you're looking for, but I found this question when trying to do something similar. You can take advantage of the fact that code in _ViewStart.cshtml
is only run when rendering a full view, so e.g. if you add
@{
ViewBag.IsFullPage = true;
}
into a _ViewStart.cshtml
file, you can then check this in your partial, e.g.
@if (ViewBag.IsFullPage != true)
{
// do something only when rendered on its own
}
So if you are rendering a partial using PartialView
from a controller endpoint, ViewBag.IsFullPage
would be false
, but if you render the partial using Html.Partial
as part of a full view, it would be true
.
Upvotes: 0
Reputation: 349
Why not @if (Layout==null)? Still I would recommend another view for the "own" page and set the layout there.
Upvotes: 7
Reputation: 6060
Based on @Pheonixblade9 's response and the lack of other answers it doesn't appear like this is possible at the moment. I ended up just binding the Model
of the View as bool
and pass this value in when rendering the view/partial.
Upvotes: 1
Reputation: 12375
In your view (assuming Razor syntax):
@if(typeof(this) == Controller.PartialView)) //code
or
@if(this is Controller.PartialView) //code
Upvotes: 1