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

依然范特西╮ 提交于 2021-01-27 19:20:32

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/57725757/what-happened-to-htmlhelpers-viewcontext-controller

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