简体   繁体   中英

What is the ASP.NET Core equivalent for @Html.IsSelected

I have to upgrade a page from ASP.NET MVC to ASP.NET Core and I have sometimes come to the hurdle that some of the old methods don't work anymore.

Is there any equivalent code to ease the upgrade proccess.

All I've found for now is @Html.Partial("name") is equal to <partial name="name.cshtml" />

The thing I have problems with is @Html.IsSelected . I can't find how to use that in ASP.NET Core

Any help would be appreciated.

You can easily fix this problem with one extension method like this:

using Microsoft.AspNetCore.Mvc.Rendering;
using System;

namespace StackOverFlow.Extensions
{
    public static class MyExtensions
    {
        public static string IsSelected(this IHtmlHelper html, string controller = null, string action = null)
        {
            string cssClass = "active";
            string currentAction = (string)html.ViewContext.RouteData.Values["action"];
            string currentController = (string)html.ViewContext.RouteData.Values["controller"];

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

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

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

and than in the view just use it:

@using StackOverFlow.Extensions;

...

<ul>
    <li class="@Html.IsSelected(action: "Index")">
        <a href="@Url.Action("Index", "Home")">Home</a>
    </li>
    <li class="@Html.IsSelected(action: "About")">
        <a href="@Url.Action("About", "Home")">About</a>
    </li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM