[英]Accessing Action information in the View
I am dynamically building a menu on my main _Layout using 我正在使用我的主_Layout动态构建菜单
@{Html.RenderAction("PageMenu", "Service");}
which adds an Menu Item for each page 为每个页面添加一个菜单项
@model int
<ul id="pages">
@for (var i = 1; i <= Model; i++) {
<li>@Html.ActionLink("Page " + i,"Page", "Service", new { page = @i}, null)/li>
}
</ul>
What I need to know is which page I am actually on so that I can indicate that on the menu. 我需要知道的是我实际上在哪个页面,以便我可以在菜单上指出。 Is there someway I can access the page # for the last clicked ActionLink? 有没有我可以访问最后一次点击ActionLink的页面#?
You could retrieve the current page number from the RouteData
: 您可以从RouteData
检索当前页码:
@model int
@functions {
IDictionary<string, object> GetHtmlAttributes(int i) {
var routeData = ViewContext.ParentActionViewContext.RouteData;
int currentPage = 0;
string page = routeData.Values["page"] as string;
var htmlAttributes = new RouteValueDictionary();
if (int.TryParse(page, out currentPage) && currentPage == i)
{
htmlAttributes["class"] = "active";
}
return htmlAttributes;
}
}
<ul id="pages">
@for (var i = 1; i <= Model; i++)
{
<li>
@Html.ActionLink(
"Page " + i,
"Page",
"Service",
new RouteValueDictionary(new { page = i }),
GetHtmlAttributes(i)
)
</li>
}
</ul>
Notice how I am using the ViewContext.ParentActionViewContext.RouteData
property instead of ViewContext.RouteData
in order to get the parent view context since you are inside a child action (you used the Html.RenderAction
helper). 请注意我是如何使用ViewContext.ParentActionViewContext.RouteData
属性而不是ViewContext.RouteData
来获取父视图上下文,因为您在子操作中(您使用了Html.RenderAction
帮助程序)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.