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

时间:2011-07-28 05:54:41

标签: asp.net-mvc asp.net-mvc-3

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

enter image description here

5 个答案:

答案 0 :(得分:9)

如果您无法访问DataTokens,则可以使用ControllerContext.IsChildAction或检查"ParentActionViewContext"是否存在包含密钥ControllerContext的内容。

答案 1 :(得分:1)

你应该可以从

获得它
HttpContext.Current.Request.RawUrl

答案 2 :(得分: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
}

答案 3 :(得分: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 !@this.OutputStack.Any(writer => writer is HttpWriter);
}

它可能不适用于所有情况。但它对我有用。 YMMV / HTH

答案 4 :(得分:0)

不,没有办法,部分不应该需要知道