有时会在给定的控制器中创建一个带有动作名称的 Enum
像这样:
public class HomeController : Controller
{
public enum Actions
{
Index,
About,
Contact,
Hosting,
Hartware
}
我在其中创建一个扩展方法并使用与我想扩展的原始类相同的命名空间,在这种情况下,我将使用 System.Web.Mvc 并创建以下类
namespace System.Web.Mvc
{
public static class MvcExtentions
{
/// <summary>
/// Generates a fully qualified URL to an action method by using the specified action Name.
/// </summary>
/// <param name="sender">used for the generate the logic</param>
/// <param name="actionName">an enum that will be used to generate the name from</param>
/// <returns>a fully qualified url to the action in the current controller</returns>
public static string Action(this UrlHelper sender, Enum actionName)
{
return sender.Action(actionName.ToString());
}
}
}
然后在我的 Razor ViewPage 中添加 Using 以到达我的页面顶部的“HomeController”,其中 ByteStream 是我的项目的名称
@using ByteStream.Web.Controllers
@{
ViewData["Title"] = "Home Page";
}
生成链接我然后使用
<a class="btn btn-default btn-default" ref="@Url.Action(HomeController.Actions.Hosting))">
Learn More
</a>