For example, here in StackOverflow you can se a top menu with the options: Questions, Tags, Users, Badges, Unanswered and Ask Question. When you are in one of those sections, it is highlighted in orange.
What is the best way to achieve that in ASP.NET MVC?
So far, and as proof of concept, I have done this helper:
public static String IsCurrentUrl(this UrlHelper url, String generatedUrl, String output)
{
var requestedUrl = url.RequestContext.HttpContext.Request.Url;
if (generatedUrl.EndsWith("/") && !requestedUrl.AbsolutePath.EndsWith("/"))
generatedUrl=generatedUrl.Substring(0, generatedUrl.Length - 1);
if (requestedUrl.AbsolutePath.EndsWith(generatedUrl))
return output;
return String.Empty;
}
That method add the output string to the element if the current request match that link. So it can be used like this:
<li>
<a href="@Url.Action("AboutUs","Home")" @Url.IsCurrentUrl(@Url.Action("AboutUs", "Home"), "class=on")><span class="bullet">About Us</span></a>
</li>
First problem, I am basically calling twice to Url.Action
, first for the "href" attribute, and after in the helper, and I think there has to be a better way to do this. Second problem, that is not the best way to compare two links. I think I could create a new Html.ActionLink
overload so I don't need to call the Url.Action
twice, but is there any buil-in way to do this?
Bonus: if I add "class="on""
, MVC renders class=""on""
. Why?
Regards.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…