How to add attribute to HTML tag depending on url in MVC application
I am presenting a list of items like:
<ul>
<li>Something 1</li>
<li>Something 2</li>
<li>Something 3</li>
<li>Something 4</li>
<li>Something 5</li>
</ul>
Depending on the route, I want to add a class to one of the tags <li>
so that I can highlight.
Maybe something like:
<ul>
<% if (this.Context.Request.RawUrl.Contains(something1Var)) { %>
<li class="highlight">
<% } else { <%>
<li>
<% } %>
Something 1</li>
<% if (this.Context.Request.RawUrl.Contains(something2Var)) { %>
<li class="highlight">
<% } else { <%>
<li>
<% } %>
Something 2</li>
<% if (this.Context.Request.RawUrl.Contains(something3Var)) { %>
<li class="highlight">
<% } else { <%>
<li>
<% } %>
Something 3</li>
<% if (this.Context.Request.RawUrl.Contains(something3Var)) { %>
<li class="highlight">
<% } else { <%>
<li>
<% } %>
Something 4</li>
<% if (this.Context.Request.RawUrl.Contains(something5Var)) { %>
<li class="highlight">
<% } else { <%>
<li>
<% } %>
Something 5</li>
</ul>
It works, but seems a little verbose. Can anyone suggest a better way to do things like this?
source to share
I would say that this kind of logic is better isolated in the controller. Consider creating a lightweight class to represent your menu items, for example:
public class MenuLinkItem {
public string Text { get; set; }
public bool Highlight { get; set; }
}
Then, in your controller method, create a list of them, set the CSS class to the selected element, and pipe the result to the view via ViewData:
public class MyController : Controller {
private MenuLinkItem MakeMenuLinkItem(string text, string urlFragment) {
return (new MenuLinkItem() {
Text = text,
Highlight = (this.Context.Request.RawUrl.Contains(urlFragment))
}
}
private IList<MenuLinkItem> GetMenuLinkItems() {
var items = new List<MenuLinkItem>();
items.Add(MakeMenuLinkItem("Something 1", something1var));
items.Add(MakeMenuLinkItem("Something 2", something2var));
items.Add(MakeMenuLinkItem("Something 3", something3var));
items.Add(MakeMenuLinkItem("Something 4", something4var));
items.Add(MakeMenuLinkItem("Something 5", something5var));
return(items);
}
public ActionResult Index() {
ViewData["menuLinkItems"] = GetMenuLinkItems();
/* other controller logic here */
return(View());
}
}
Then, in your actual view code, you will create your menu like this:
<ul>
<% foreach(var item in (IList<LinkMenuItem>)ViewData["menuLinkItems"])) { %>
<li <%= item.Highlight ? "class=\"highlight\"" : ""%>><%=item.Text%></li>
<% } %>
</ul>
The controller makes decisions about which links are highlighted and the view translates those decisions into an HTML / CSS presentation that makes sense to your users.
source to share