Question

I'm hoping this is a duplicate, but my searches haven't found an answer so far.

Is there an easy way to tell from within a razor view, whether or not it was rendered as a partial? Without setting a property in the model or ViewBag / ViewData to tell it?

For example, you might have something like this:

public ActionResult SometimesPartialSometimesNot()
{
    return ControllerContext.IsChildAction ? PartialView() : View();
}

Now I know you can access IsChildAction from the view's ViewContext, but say somewhere else in the site you have this:

Html.RenderPartial("SometimesPartialSometimesNot", new CustomModel());

Given all of the above, is there an easy way to tell from within the SometimesPartialSometimesNot view, whether it was rendered as a partial (from either an action or another view)?

Was it helpful?

Solution

Is there an easy way to tell from within a razor view, whether or not it was rendered as a partial?

Nope, there's no way, other than passing this information as a model value (or ViewData). By the way when you give it a second thought, that would make your code even better, because the partial won't depend on the fact whether it was rendered as partial using the RenderPartial helper or in some other manner. It is self dependent (on its view model only) -> the way all views should be.

Note: this is possible with child actions which will populate the ParentActionViewContext property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top