MVC 6中的HtmlHelpers

时间:2014-12-02 19:14:58

标签: c# asp.net-core asp.net-core-mvc

我试图将此代码移植到mvc 6,感谢任何帮助,代码编译但该方法在@Html.IsActive的观点中不可用。

using Microsoft.AspNet.Mvc.Rendering;

namespace Blah.Web.Helpers
{
    public static class HtmlHelpers
    {

        public static string IsActive(this HtmlHelper htmlHelper, string controller, string action)
        {
            var routeData = htmlHelper.ViewContext.RouteData;

            var routeAction = routeData.Values["action"].ToString();
            var routeController = routeData.Values["controller"].ToString();

            var returnActive = (controller == routeController && action == routeAction);

            return returnActive ? "active" : "";
        }

    }
}

在视图中,我引用了名称空间:

@using Blah.Web.Helpers;

1 个答案:

答案 0 :(得分:19)

在方法签名中,HtmlHelper应为IHtmlHelper

参见下面的示例

namespace Blah.Web.Helpers
{
    public static class HtmlHelpers
    {
        public static string IsActive(this IHtmlHelper htmlHelper, string controller, string action)
        {
            var routeData = htmlHelper.ViewContext.RouteData;

            var routeAction = routeData.Values["action"].ToString();
            var routeController = routeData.Values["controller"].ToString();

            return (controller == routeController && action == routeAction) ? "active" : "";
        }
    }
}