MVC – Going Crazy With Dynamic Methods!
August 20th, 2010 / No Comments » / by Mike
I recently finished a Project in MVC 2 and .NET 4.0. This project was basically a website with an admin section. Nothing special…
But the client wanted his navigation menu to have a different image button for every menu item… and it has rollover effect with another image button… This is not a big challenge but It was a pain in the ass to do this the old fashion way!
So I decided to have fun with some new stuff instead!
I started by putting all the menu items in an array:
var menuItems = new [] {
new {
Name = "Home",
isActive = SetActiveStatus("Home"),
CssClass = "btn-darkBlue",
ActiveCssClass = "btn-darkBlue-active"
},
new {
Name = "Careers",
isActive = SetActiveStatus("Careers"),
CssClass = "btn-lightBlue",
ActiveCssClass = "btn-lightBlue-active"
},
new {
Name = "Services",
isActive = SetActiveStatus("Services"),
CssClass = "btn-green",
ActiveCssClass = "btn-green-active"
},
new {
Name = "News",
isActive = SetActiveStatus("News"),
CssClass = "btn-orange",
ActiveCssClass = "btn-orange-active"
},
new {
Name = "About",
isActive = SetActiveStatus("About"),
CssClass = "btn-red",
ActiveCssClass = "btn-red-active"
},
new {
Name = "Contact",
isActive = SetActiveStatus("Contact"),
CssClass = "btn-purple",
ActiveCssClass = "btn-purple-active"
}
};
As you can see Menu Items are actually dynamic objects with their Name, their Status, their Css Class and their Active Css Class.
SetActiveStatus(“Contact”) is a dynamic method I created to find out where I’m located on the site, to set the status of the right menu item. This is fairly simple:
FuncSetActiveStatus = c => (c == area);
So basically this is method which requires a string and sends you back a bool if the string you input is the same as area.
Once this was done I needed the HTML markup for my menu, so here goes: (I was having difficulty with Syntax Highlighter here. Seems it doesn’t like a mix of languages! Click the image to enlarge)
Every link looks like this:
Html.RouteLink("Careers",
"Careers_Home",
null,
new {
@class = GetActiveStatus("Careers")
? GetActiveCssClass("Careers")
: GetCssClass("Careers")
}
)
What this does is make a link from my routes with a CSSclass depending on the status of the item I want to display.
FuncGetActiveStatus = c => (menuItems.Where(x => x.Name == c).First().isActive); Func GetActiveCssClass = c => (menuItems.Where(x => x.Name == c).First().ActiveCssClass); Func GetCssClass = c => (menuItems.Where(x => x.Name == c).First().CssClass);
This is probably VERY overkill for a 6 items menu, but it was fun writing =)







