您可以从以下位置检索当前页码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>
请注意我是如何使用ViewContext.ParentActionViewContext.RouteData
属性而不是ViewContext.RouteData
为了获取父视图上下文,因为您在子操作中(您使用了Html.RenderAction
帮助器)。