Bootstrap framework is currently the most popular framework (or rather a set of themes and controls) which makes creating of the responsive websites very easy. Unfortunately, some effects on the website are not easy to reach in caseyou want to create a ASP.NET MVC web application using the partial views. One of them is setting of the specific style on the Bootstrap navbar "li" active element.
You can obviously achieve the desired style on the active "li" element of the navbar by using a Javascript function which would check what page was loaded by the address (or e.g. the content) and set the class on the element, but it is complicated and not very elegant solution.
The best way, to achieve the mentioned effect is to use the extended MenuLink method on the ASP.NET backend of the application.
Changes on the UI
Firstly, we need to use a MenuLink in the Bootstrap menu. so it would look like more-less like this:
In the example I have replaced ActionLinks with Menu links. Without backend changes it won't give us a result, but now we will add an Extension method o the backend.
Changes on the backend
Lets create a new class, which will hold all of the helpers, which may be used on the UI directly. In case of our problem, we will an extension method for the MVC MenuLink. The code of the method is below.
using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Routing; public static class HtmlHelpers { //Extensibl method MenuLink public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName) { //Create a tag, that will be an action link inside a "li" element TagBuilder builder = new TagBuilder("li") { InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToHtmlString() }; //Get current routes from the context of the view. RouteData route = htmlHelper.ViewContext.RouteData; //Gets the controller and the action from the route data string action = route.GetRequiredString("action"); string controller = route.GetRequiredString("controller"); //If the current controller and action are the same as the element on the navbar menu, //then we need to add the class "active" on the tag. if (controllerName == controller && actionName == action) { builder.AddCssClass("active"); } return new MvcHtmlString(builder.ToString()); } }
This simple and elegant solution will make application niecer and the management will be much easier. You won't need to touch the mechanism of setting of the Bootstrap active classes any more.
0 comments:
Post a Comment