Search code examples
c#asp.net-core

Extension method to get a controller name without suffix


I don't want to repeat the following

nameof(HomeController).Replace(nameof(Controller), string.Empty)

everytime I need to supply controller name without suffix "Controller".

Is there any elegant way to simplify? I attempted to create an extension method as follows but I don't know how to get the instance of the controller in question from a cshtml view.

using Microsoft.AspNetCore.Mvc;

namespace WebApplication1
{
    public static class Utilities
    {
        public static string BareName(this Controller controller)
        {
            return nameof(controller.GetType).Replace(nameof(Controller), string.Empty);
        }
    }
}

I want to invoke the following, for example, in view page.

@Html.ActionLink("something", nameof(HomeController.someaction), nameof(HomeController).Replace(nameof(Controller), string.Empty))

Solution

  • You could create a separate extension method on ActionContext which resolves the controller name from the ActionDescriptor.

    public static string GetControllerName(this ActionContext actionContext)
    {
        return (actionContext.ActionDescriptor as ControllerActionDescriptor)?.ControllerName;
    }
    

    You don't need to trim the "Controller" part from the string in this case. Call it in your view like this:

    var controllerName = ViewContext.GetControllerName();