Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlHelpers in MVC 6

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;
like image 320
RickJames Avatar asked Dec 02 '14 19:12

RickJames


People also ask

What are the HTML helpers we have?

HTML Helpers are methods that return a string. Helper class can create HTML controls programmatically. HTML Helpers are used in View to render HTML content. It is not mandatory to use HTML Helper classes for building an ASP.NET MVC application.

Can we use tag helpers in MVC 5?

No, tag helpers are only supported in ASP.NET Core, not in the older ASP.NET (based on the classic . NET Framework, rather than the newer . NET Core). But instead you can use HTML Helpers which do a lot of the same things.


1 Answers

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" : "";
        }
    }
}
like image 152
Son_of_Sam Avatar answered Oct 27 '22 12:10

Son_of_Sam