HtmlHelpers in MVC 6

情到浓时终转凉″ 提交于 2019-12-21 10:58:26

问题


I'm trying to port this code over to mvc 6, any help is appreciated, the code compiles but the method is not available in my views on @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" : "";
        }

    }
}

In the View I have the namespace referenced:

@using Blah.Web.Helpers;

回答1:


In the method signature, HtmlHelper should be IHtmlHelper

See Example below

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" : "";
        }
    }
}


来源:https://stackoverflow.com/questions/27257133/htmlhelpers-in-mvc-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!