blakcat
blakcat

Reputation: 716

Read URL parameter for Helpers

There are Helpers who are responsible for adding Active classes to the menu.

public static class HtmlHelpers
{
    public static string IsSelected(this IHtmlHelper html, string controller = null, string action = null, string status = null, string cssClass = null)
    {
        if (String.IsNullOrEmpty(cssClass))
            cssClass = "active";

        string currentAction = (string)html.ViewContext.RouteData.Values["action"];
        string currentController = (string)html.ViewContext.RouteData.Values["controller"];
        string currentStatus = (string)html.ViewContext.RouteData.Values["status"];


        if (String.IsNullOrEmpty(controller))
            controller = currentController;

        if (String.IsNullOrEmpty(action))
            action = currentAction;

        if (String.IsNullOrEmpty(status))
            status = currentStatus;

        return controller == currentController && action == currentAction && status == currentStatus ?
            cssClass : String.Empty;
    }

    public static string PageClass(this IHtmlHelper htmlHelper)
    {
        string currentAction = (string)htmlHelper.ViewContext.RouteData.Values["action"];
        return currentAction;
    }

}

While standard URL parameters ("controller} / {action} / {id?}" are involved, everything works fine. But how to read the variables in the URL.

Is https://localhost:/Contractors?Status=false

How to get STATUS data

P.S. For those who later want to use Helper. CHTML

<li class="@Html.IsSelected(action: "Index", controller: "Contractors", status: "true")"><a asp-action="Index" asp-controller="Contractors" asp-route-status="true">Clients</a></li>

Upvotes: 0

Views: 250

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46591

RouteData only contains values from extracted from the route. So unless you add the status parameter to the route (e.g. /contractors/{status}) you can't retrieve the value from the route data.

In this case it's a regular query-string parameter which you can retrieve from ViewContext.HttpContext.Request:

var status = html.ViewContext.HttpContext.Request.Query["status"].ToString();

Upvotes: 1

Related Questions