ASP.NET MVC: partially knows if it is being requested from another page?

I have a partial view that can be requested via Action (Action2 in the image below) or displayed inside another page using "Html.Action ()" (Action1 in the image below). From a partial (or partial controller), is there a way to determine which of these two methods was used to render the page?

enter image description here

+6
source share
5 answers

You can use ControllerContext.IsChildAction or check DataTokens if there is something with the key "ParentActionViewContext" if you do not have access to ControllerContext .

+9
source

You can get it from

 HttpContext.Current.Request.RawUrl 
+1
source

It should be noted that in MVC it ​​is not a good practice to do such things. Partial does not have to worry about his "parent" ... but if you need to do this for any reason ...

You can use this code in the partial view controller to determine if it was loaded directly or included in another page.

 // this is the route which was originally used to route the request string req_controller = Request.RequestContext.RouteData.Values["controller"].ToString(); string req_action = Request.RequestContext.RouteData.Values["action"].ToString(); // this is the route which was used to route to this action/view string this_controller = RouteData.Values["controller"].ToString(); string this_action = RouteData.Values["action"].ToString(); if (req_controller == this_controller && req_action == this_action) { // this partial was loaded directly } else { // this partial was loaded indirectly } 
+1
source

My reason I want to know this is because I would like to switch the Layout partial view based on whether it was displayed from a controller action or from another page.

t

 return PartialView("MyView.cshtml"); 

will lead to the layout with the necessary menu stripes and other crop sites.

and

 @Html.Partial("MyView") 

just embeds the content without adding the rest of the page.

so in my default Layout page I have:

 @if (this.IsPartial()) { Layout = null; } else { Layout = "_SiteLayout"; } @RenderBody() 

here is what i found:

 public static bool IsPartialResult(this WebPageBase @this) { return !@this.OutputStack.Any (writer => writer is HttpWriter); } 

it probably won’t work in all situations. but it works for me. YMMV / NTN

+1
source

No, there is no way, and partial should not know this.

0
source

Source: https://habr.com/ru/post/893745/


All Articles