Conditionally Change Background Color on Menu Item

Hi,

I have a simple menu that is used to navigate to different views on my web site.  My goal was to have the background color of the menu item change if you are on that view.  For example, let's say that the menu has two items: Index 1 and Index 2.  If I'm on Index 1 the background color of "Index 1" in the menu should be different then all the other menu items.  That way you would know where you are by looking at the menu.

I figured out a simple way to do this and thought I'd share in case it helps anyone else out.

Step 1

Create a partial view for the menu control. The partial view automatically inherits "ViewData" from the parent view.  Set a value in the parent ViewData so the partial view knows what the parent view is.  Conditionally set "html-attributes" to change the background color of the menu item.  For example:

_MyMenu.cshtml

<div id="MyMenuDiv">
    <ej-menu id="MyMenu">
        <e-menu-items>
            <e-menu-item id="Index1" text="Index 1" url="/Home/Index" html-attributes=@(ViewData["MenuItem"].ToString() == "Index1" ? new Dictionary<string, object>() { { "style","background-color:lightsteelblue"} } : null)></e-menu-item>
            <e-menu-item id="Index2" text="Index 2" url="/Home/Index2" html-attributes=@(ViewData["MenuItem"].ToString() == "Index2" ? new Dictionary<string, object>() { { "style","background-color:lightsteelblue"} } : null)></e-menu-item>
        </e-menu-items>
    </ej-menu>
</div>

Step 2

Create your parent views.  Set ViewData["MenuItem"] and render the partial view.

For example:

Index.cshtml

@{
    ViewData["Title"] = "Index 1";
    ViewData["MenuItem"] = "Index1";
}
<h2>Index 1</h2>
@await Html.PartialAsync("_MyMenu")

Index2.cshtml

@{
    ViewData["Title"] = "Index 2";
    ViewData["MenuItem"] = "Index2";
}
<h2>Index 2</h2>
@await Html.PartialAsync("_MyMenu")

Chris


1 Reply

IB Ilakkiya Baskar Syncfusion Team June 29, 2018 04:54 AM UTC

Hi Chris, 
  
We are glad your problem has been solved. Please let us know if you need any assistance 
  
Regards 
Ilakkiya 


Loader.
Up arrow icon