這應該是剛開始學ASP.NET MVC 常犯的錯誤,一般我們會新增一個資料夾”Helpers”來放 HtmlHelper的程式,如在資料夾新增一個class,如:HMTLHelperExtensions.cs。
using System; using System.Web.Mvc; namespace DemoCustomIndentity.Helpers { public static class HMTLHelperExtensions { public static string IsSelected(this HtmlHelper html, string controller = null, string action = null, string cssClass = null) { if (String.IsNullOrEmpty(cssClass)) cssClass = "active"; string currentAction = (string)html.ViewContext.RouteData.Values["action"]; string currentController = (string)html.ViewContext.RouteData.Values["controller"]; if (String.IsNullOrEmpty(controller)) controller = currentController; if (String.IsNullOrEmpty(action)) action = currentAction; return controller == currentController && action == currentAction ? cssClass : String.Empty; } public static string PageClass(this HtmlHelper html) { string currentAction = (string)html.ViewContext.RouteData.Values["action"]; return currentAction; } } }