Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 897
Jez Avatar asked May 28 '26 00:05

Jez


1 Answers

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;
}
like image 78
Darjan Bogdan Avatar answered May 30 '26 13:05

Darjan Bogdan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!