asp.net-mvc – HtmlHelper获取路由名称
发布时间:2020-12-16 09:57:43 所属栏目:asp.Net 来源:网络整理
导读:我创建了一个html帮助程序,如果用户在当前页面上,则会向li项添加css类属性.助手看起来像这样: public static string MenuItem( this HtmlHelper helper,string linkText,string actionName,string controllerName,object routeValues,object htmlAttributes
我创建了一个html帮助程序,如果用户在当前页面上,则会向li项添加css类属性.助手看起来像这样:
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 routeName,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,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实例进行比较. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读