ASP.NET Adding Class to Current Menuitem

asp.net adding class to current menuItem

You won't need to track the page using session variables, as when you select a menu item, asp.net kindly tracks the item you've selected and generates its own CSS class for you (in most cases). To get a better visual download firebug for Firefox and look at the HTML output, you'll see they'll have CSS styles attached such as "asp-net.menu selectedItem" for example, you then create a .selectedItem{} CSS class, and then it will pick up the style automatically.

However If I recall it can be a bit fiddly styling Microsoft controls, as if you check the source code out of the output, its not exactly HTML friendly.

If you want to style the Menu item using the Microsoft approach, go here http://msdn.microsoft.com/en-us/library/ms366731.aspx

However there is a library called CSSfriendly http://cssfriendly.codeplex.com/ that renders the control in pure HTML, which allows you to attach CSS classes much more easily. For example:

.CssAdapterMenu ul.AspNet-Menu /* Tier 1 */
{
width: 961px !important;
cursor:pointer;
background-color:#000000;
}

.CssAdapterMenu ul.AspNet-Menu ul /* Tier 2 */
{
left: 0;
background-color:#f8f8f8;
width: 145% !important;
max-width: 160px !important;
}

.CssAdapterMenu ul.AspNet-Menu ul li:hover /* Tier 2 cell */
{
background: #636363 url(../images/menu_bg_hover.png) no-repeat !important;
}

.CssAdapterMenu ul.AspNet-Menu ul .AspNet-Menu-Selected{
background: transparent url(../images/menu_bg_hover.png) no-repeat !important;
}

.CssAdapterMenu li.AspNet-Menu-WithChildren li .AspNet-Menu-ChildSelected {
background: transparent url(../images/menu_bg_hover.png) no-repeat !important;
}

And so on and so forth. Theres good documentation out there for this, and its my preferred method for styling.

Amended your code with my explanations below.

<asp:Menu ID="mainMenu" runat="server" autopostback="true">
<Items>
<asp:MenuItem Text="Home" Value="Home" ></asp:MenuItem>
<asp:MenuItem Text="Pipes" Value="Pipes"></asp:MenuItem>
<asp:MenuItem Text="View & Query" Value="View & Query</asp:MenuItem>
<asp:MenuItem Text="API" Value="API"></asp:MenuItem>
</Items>
<StaticMenuItemStyle CssClass="menuItem" />
<StaticSelectedStyle CssClass="selectedItem" />
<StaticHoverStyle CssClass="hoverItem" />
</asp:Menu>

Then in your CSS:

.normal{ 
background-color:#eaeaea;
}

.selected {
background-color:#000000;
}

.hover{
background-color:#FF0000;
}

asp.net menuitem add class

MenuItem doesn't have a CSS class property, instead add the class to the parent Menu:

Menu menu = new Menu();
menu.CssClass = "myclass";

If you want to dynamically add classes to the menu then try creating a helper method (Extension Methods in C#):

public static class MenuExtension
{
public static void AddCSSClass(this Menu menu, string className)
{
// additional code here to tidy / remove duplicates etc.

menu.CssClass = string.Concat(menu.CssClass, " ", className);
}
}

Since our Menu renders a UL you can then use CSS selectors to cascade the style to all child LI elements:

.myclass > li {
// your attributes
}

Or alternatively, specific LI elements (things like nth-child etc are only supported in CSS 3.0):

.myclass > li:first-child {
// your attributes
}

.myclass > li:nth-child(1) {
// your attributes
}

How do I make current menu item active in asp.net webforms

If you are talking about serverside you should to add property to your control and method to detect if it's specified page

    public string CurrentPageName { get; set; }

public string IsCurrentPage(string itemName)
{
return CurrentPageName == itemName ? "class='active'" : string.Empty;
}

and on the page declare control in such way

    <uc:YourMenuControl runat="server" CurrentPageName="Your Current Page" />

and update your li items like

    <li <%= IsCurrentPage("500.html")  %>><a href="500.html"><i class="fa fa-circle-o"></i> 500 Error</a></li>
<li <%= IsCurrentPage("blank.html") %>><a href="blank.html"><i class="fa fa-circle-o"></i> Blank Page</a></li>

if you can use server controls you can make it in slightly different way, setup your li items in collection and add it to your server control

    <ul class="treeview-menu" runat="server" id="myMenu"></ul>

control codebehind, here we set value for CurrentPageName in codebehind

    protected void Page_Load(object sender, EventArgs e)
{
CurrentPageName = "blank.html";
var menuItemsList = new Dictionary<string, string>()
{
{"invoice.html", " Lockscreen"},
{"lockscreen.html", " Lockscreen"},
{"blank.html", " Blank"}
};

foreach (var item in menuItemsList)
{
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlGenericControl ianchor = new HtmlGenericControl("a");
ianchor.Attributes.Add("href", item.Key);
if (CurrentPageName == item.Key)
{
ianchor.Attributes.Add("class", "active");
}

HtmlGenericControl i = new HtmlGenericControl("i");
i.Attributes.Add("class", "fa fa-circle-o");
ianchor.InnerText = item.Value;
ianchor.Controls.AddAt(0, i);
li.Controls.Add(ianchor);
myMenu.Controls.Add(li);
}
}

How to set css class on active menu item using a masterpage?

Here is what I do. There could be a better way. You can try it.

NOTE: your link should have runat="server" so you can access them from code-behind

protected void Page_Load(object sender, EventArgs e)
{
string curlink = Request.RawUrl;

if (curlink.Contains("/administration/school"))
{
schoolinfolink.Attributes["class"] = "selected";
}
else if (curlink.Contains("/administration/result"))
{
resultlink.Attributes["class"] = "selected";
}
else if (curlink.Contains("/administration/staff"))
{
staffslink.Attributes["class"] = "selected";
}

}

.NET MVC C# - Add class to current menu item

This is just a string:

"list-group-item wb-sec-h3 h3 Html.CurrentItem(\"Search\", \"Home\")"

It may contain what looks like code to a human, but .NET isn't going to execute that code. It's just a string.

In order to execute code, you have to remove it from the string and concatenate its result to the literal string. Which might look something like this:

"list-group-item wb-sec-h3 h3 " + Html.CurrentItem("Search", "Home")

applying css class to menu item at run time in mvc

If you want to change the css based on Action or Controller you can use

@{
var controller = ViewContext.RouteData.Values["Controller"].ToString();
var action = ViewContext.RouteData.Values["Action"].ToString();
}

<li>
@if (action == "Home") {
@Html.ActionLink("Home", "Index", new { Controller = "Home" },new {@class="active" })
}
else {
@Html.ActionLink("Home", "Index", new { Controller = "Home" })
}
</li>
<li>
@if (action == "About Us") {
@Html.ActionLink("About Us", "About", new { Controller = "Home" },new {@class="active" })
}
else {
@Html.ActionLink("About Us", "About", new { Controller = "Home" })
}
</li>

etc...

How do I make current menu item active in asp.net webforms masterpage using jquery or javascript

You can put a hidden field in the master page that holds the id of the current tab (parent li). Then set the value of that hidden field in the content pages.

Use the hidden field's value to determine which tab to highlight. This code assumes the parent ul has id="MasterMenu" and does not have runat="server". Also that the hidden field has id="CurrentTab".

function highlightTab() {
var currentTab;

//Get the id of the current tab from the hidden field
currentTab = $('#CurrentTab').val();

if (currentTab !== null) {
//Remove the active-treeview class from all top level li elements
$('#MasterMenu').children('li').removeClass('active-treeview');

//Set the active-treeview class to the current tab
$('#' + currentTab).addClass('active-treeview');
}
}

EDIT:
Here is an example of a hidden field that you would put on your master page. I'm making it available to the code behind by adding the runat="server" attribute. When a control has runat="server", .NET will rename the id when it renders the page. To stop this behavior so you can easily access the hidden field in JavaScript add the ClientIDMode="static" attribute.

<asp:HiddenField id="CurrentTab" value="" runat="server" ClientIDMode="static" />

In the page load event of your content pages set the value of that hidden field to the id of the tab you want highlighted for that page.

HiddenField currentTab;
currentTab = (HiddenField)this.Master.FindControl("CurrentTab");
currentTab.Value = "settingId";


Related Topics



Leave a reply



Submit