ASP.NET MVC:部分知道它是否从另一个页面带来请求?

问题描述 投票:6回答:5

我有一个局部视图,可以通过Action(下图中的Action2)请求,也可以在另一个页面中使用“Html.Action()”(下图中的Action1)进行渲染。从部分(或部分控制器)内部有一种方法可以确定这两种方法中的哪一种用于呈现页面?

asp.net-mvc asp.net-mvc-3
5个回答
9
投票

如果你无法访问ControllerContext.IsChildAction,你可以使用DataTokens或检查"ParentActionViewContext"是否有关键ControllerContext的东西。


1
投票

你应该能够从中得到它

HttpContext.Current.Request.RawUrl

1
投票

应该注意的是,在MVC中做这种事情并不是特别好的做法。部分不应该关注它的“父母”......但如果你确实需要这样做,无论出于什么原因......

您可以在局部视图的控制器中使用此代码来确定它是直接加载还是包含在另一个页面中。

// 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
投票

我想知道这个的原因是我希望能够根据它是从控制器动作还是从另一个页面内部渲染来切换部分视图的Layout

即。

return PartialView("MyView.cshtml");

会导致布局与必要的菜单栏和其他网站装饰。

@Html.Partial("MyView")

只是嵌入内容而不添加页面的其余部分。

所以,在我的页面默认布局中我有:

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

这是我发现的:

public static bool IsPartialResult(this WebPageBase @this)
{
    return [email protected](writer => writer is HttpWriter);
}

它可能不适用于所有情况。但它对我有用。因人而异/ HTH


0
投票

不,没有办法,部分不应该知道它。

© www.soinside.com 2019 - 2024. All rights reserved.