【发布时间】:2019-02-05 16:43:17
【问题描述】:
我不想重复以下内容
nameof(HomeController).Replace(nameof(Controller), string.Empty)
每次我需要提供不带“控制器”后缀的控制器名称时。
有什么优雅的方法可以简化吗?我尝试按如下方式创建扩展方法,但我不知道如何从 cshtml 视图中获取相关控制器的实例。
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);
}
}
}
我想调用以下内容,例如,在视图页面中。
@Html.ActionLink("something", nameof(HomeController.someaction), nameof(HomeController).Replace(nameof(Controller), string.Empty))
【问题讨论】:
-
您不能在控制器的方法中调用
this.BareName()并将返回值添加到传递给te cshtml 视图的ViewBag吗? -
@PietroMartinelli:但使用
ViewBag容易出错。
标签: c# asp.net-core