In the default asp.net mvc project, in the Site.Master file, there is a menu navigation list:
Using MVC3 with a Razor View offers another option:
_Layout.cshtml:
<li class="@ViewBag.NavClassHome">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@ViewBag.NavClassAbout">@Html.ActionLink("Disclaimer", "About", "Home")</li>
HomeController:
public ActionResult Index() {
ViewBag.NavClassHome = "active";
return View();
}
public ActionResult About() {
ViewBag.NavClassAbout = "active";
return View();
}
If you want to preserve this for a postback as well, you have to assign the ViewBag value here as well:
[HttpPost]
public ActionResult Index() {
ViewBag.NavClassHome = "active";
return View();
}
[HttpPost]
public ActionResult About() {
ViewBag.NavClassAbout = "active";
return View();
}
Tested and working fine for me, but you will have a css class name in your server side code.
An old question but hopefully someone might find this very helpful.
For example, in index.cshtml, put something like
@{
ViewBag.PageName = "Index";
}
<li class="@((ViewBag.PageName == "Index") ? "active" : "")"><a href="@Url.Action("Index","Home")">Home</a></li>
<li class="@((ViewBag.PageName == "About") ? "active" : "")"><a href="@Url.Action("About","Home")">About</a></li>
<li class="@((ViewBag.PageName == "Contact") ? "active" : "")"><a href="@Url.Action("Contact","Home")">Contact</a></li>
I didn't just test it, I use this method in my projects
Using MVC3 with a Razor View, you can implement this like:
<ul id="menu">
@if (ViewContext.RouteData.Values["action"].ToString() == "Index")
{
<li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
}
else
{
<li>@Html.ActionLink("Home", "Index", "Home")</li>
}
@if (ViewContext.RouteData.Values["action"].ToString() == "About")
{
<li class="active">@Html.ActionLink("About", "About", "Home")</li>
}
else
{
<li>@Html.ActionLink("About", "About", "Home")</li>
}
</ul>
And then applying your style of your ".active" class like:
ul#menu li.active
{
text-decoration:underline;
}