Kevin
Kevin

Reputation: 4747

Accessing Action information in the View

I am dynamically building a menu on my main _Layout using

 @{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?

Upvotes: 0

Views: 46

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039398

You could retrieve the current page number from the 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).

Upvotes: 2

Related Questions