我创建了一个 html 帮助器,如果用户位于当前页面,它会将 css 类属性添加到 li 项。助手看起来像这样:
public static string MenuItem( this HtmlHelper helper, string linkText,
string actionName, string controllerName, object routeValues, object htmlAttributes )
{
string currentControllerName =
( string )helper.ViewContext.RouteData.Values["controller"];
string currentActionName =
( string )helper.ViewContext.RouteData.Values["action"];
var builder = new TagBuilder( "li" );
// Add selected class
if ( currentControllerName.Equals( controllerName, StringComparison.CurrentCultureIgnoreCase ) &&
currentActionName.Equals( actionName, StringComparison.CurrentCultureIgnoreCase ) )
builder.AddCssClass( "active" );
// Add link
builder.InnerHtml = helper.ActionLink( linkText, actionName, controllerName, routeValues, htmlAttributes );
// Render Tag Builder
return builder.ToString( TagRenderMode.Normal );
}
我想扩展这个类,这样我就可以将路由名称传递给助手,如果用户位于该路由上,那么它会将 css 类添加到 li 项目中。但是我很难找到用户所在的路线。这可能吗?到目前为止我的代码是:
public static string MenuItem( this HtmlHelper helper, string linkText, string routeName, object routeValues, object htmlAttributes )
{
string currentControllerName =
( string )helper.ViewContext.RouteData.Values["controller"];
string currentActionName =
( string )helper.ViewContext.RouteData.Values["action"];
var builder = new TagBuilder( "li" );
// Add selected class
// Some code for here
// if ( routeName == currentRoute ) AddCssClass;
// Add link
builder.InnerHtml = helper.RouteLink( linkText, routeName, routeValues, htmlAttributes );
// Render Tag Builder
return builder.ToString( TagRenderMode.Normal );
}
顺便说一句,我正在使用 MVC 1.0。
谢谢
最佳答案
名称并不直接是路由的属性;它们只是集合将字符串映射到路由的一种方式。所以你无法从当前路由中获取路由名称。
但是您可以比较路线本身,而不是使用名称。由于您拥有当前的 RouteBase 实例(您可以通过 HtmlHelper.ViewContext.RouteData.Route 获取它)和 RouteCollection(通过 HtmlHelper.RouteCollection),因此您可以使用 RouteCollection.Item获取目标路由名称对应的RouteBase。将返回的 RouteBase 实例与当前的 RouteBase 实例进行比较。
关于asp.net-mvc - HtmlHelper 获取路由名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2562644/