3

I had an HTML extension in .NET 4.6 like this one

public static string IsSelected( this HtmlHelper html, string controller = null, string action = null, string area = null ) {
    string cssClass = "active";
    string currentAction = (string)html.ViewContext.RouteData.Values[ "action" ];
    string currentController = (string)html.ViewContext.RouteData.Values[ "controller" ];
    string currentArea = html.ViewContext.RouteData.DataTokens[ "area" ] == null ? String.Empty : (string)html.ViewContext.RouteData.DataTokens[ "area" ];

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

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

    if ( String.IsNullOrEmpty( area ) )
        area = currentArea;

    if ( controller.ToLower() == currentController.ToLower() && action.ToLower() == currentAction.ToLower() && area == currentArea ) {
        return cssClass;
    }
    else {
        return string.Empty;
    }
}

Through this helper I was able to write code like this in a razor view:

<li class="treeview @Html.IsSelected( controller: "mycontroller", action : string.Empty, area : string.Empty )">
    <a href="#">
        <i class="fa fa-list-alt"></i> <span>Menu 1</span>
        <span class="pull-right-container">
            <i class="fa fa-angle-right pull-right"></i>
        </span>
    </a>
    <ul class="treeview-menu">
        <li class="@Html.IsSelected( controller: "mycontroller", action : "myaction", area : string.Empty )">
            <a href="@Url.Action("myaction", "mycontroller" )">
                <i class="fa fa-retweet"></i>
                My Action &nbsp;
            </a>
        </li>
    </ul>
</li>

How can I convert this helper to be used with .NET Core? I have tried by using IHtmlContent but I cannot get the ViewContext. The only way is a tag helper?

3
  • did you find a way to get the viewcontext? Commented Jul 22, 2018 at 11:32
  • unfortunately not. I have setup my code into a TagHelper. Commented Jul 29, 2018 at 9:49
  • 1
    check this out then: stackoverflow.com/questions/42039269/… Commented Jul 29, 2018 at 15:17

1 Answer 1

3

Maybe quite late, but you can get it via:

this.ViewContext

when you are within a cshtml file

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.