Search code examples
c#asp.netasp.net-core.net-corehtml-helper

What happened to HtmlHelper's 'ViewContext.Controller'?


In my old ASP.NET web app, I coded an HTML helper to get access to the context of the controller executing the current view by accessing ViewContext.Controller:

public static string GetControllerString(this HtmlHelper htmlHelper) {
    string controllerString = htmlHelper.ViewContext.Controller.ToString();
    return ".NET Controller: " + controllerString;
}

However, this no longer seems to exist in ASP.NET Core's HTML helper object:

public static string GetControllerString(this IHtmlHelper htmlHelper) {
    string controllerString = htmlHelper.ViewContext.Controller.ToString(); // Doesn't exist!
    return ".NET Core Controller: " + controllerString;
}

What happened to ViewContext.Controller? Is it now impossible to get hold of the controller context from the HTML helper object?


Solution

  • They've changed inheritance chain and terminology a bit. So, ViewContext in ASPNET Core doesn't inherit from ControllerContext, like in the older ASPNET MVC framework.

    Instead, ViewContext inherits from ActionContext which is more generic term.

    Due to that fact, there is no inherited Controller property on the ViewContext object, but rather you can use ActionDescriptor property, to get the needed value.

    public static string GetControllerString(this IHtmlHelper htmlHelper) {
        string actionDescriptor = htmlHelper.ViewContext.ActionDescriptor.DisplayName;
        return ".NET Core Controller: " + actionDescriptorName;
    }