Monday, 13 February 2012

ASP.NET MVC: Adding active tag for html elements

 public static MvcHtmlString SelectedLink(this HtmlHelper helper, string linkText, string actionName, string controlName, string activeClassName, int id)
{
if (helper.ViewContext.RouteData.Values["action"].ToString() == actionName &&
helper.ViewContext.RouteData.Values["controller"].ToString() == controlName)
return helper.ActionLink(linkText, actionName, controlName, new { Class = activeClassName, Id = id });

return helper.ActionLink(linkText, actionName, controlName);
}
or 
 
        public static MvcHtmlString ActiveMenuItem(this HtmlHelper helper, string linkText, string actionName, string controllerName, int id)
{
TagBuilder li = new TagBuilder("li");

RouteData routedata = helper.ViewContext.RouteData;
string currentAction = routedata.GetRequiredString("action");
string currentController = routedata.GetRequiredString("controller");
int currentId = ConvertionHelper.GetConvertedValue<int>(routedata.GetRequiredString("id"));

if (string.Equals(currentAction, actionName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controllerName, StringComparison.OrdinalIgnoreCase) &&
int.Equals(currentId, id))
{
li.AddCssClass("active");
}

li.InnerHtml = helper.ActionLink(linkText, actionName, new { Id = id }).ToHtmlString();

return MvcHtmlString.Create(li.ToString());
}

No comments:

Post a Comment