开发者

Changing the selected Menu items class across pages

开发者 https://www.devze.com 2023-04-07 06:21 出处:网络
For my website project I am using ASP.NET MVC \"Razor\". Learning as I go. I have 5 or 6 pages on my site, and one page that is on another site.I want users to feel like they are using the same site

For my website project I am using ASP.NET MVC "Razor". Learning as I go.

I have 5 or 6 pages on my site, and one page that is on another site. I want users to feel like they are using the same site for all.

There is a typical HTML menu for the pages which follows the standard pattern of using a XHTML unordered list and CSS to layout:

<ul id="menu">
    <li class="selected"><a href="@Href("~/")">Home</a></li>
    <li><a href="http://ceklog.kindel.com">cek.log</a></li>
    <li><a href="@Href("~/Services")">Services</a></li>
    <li><a href="@Href("~/Charlie")">Charlie's Stuff</a></li>
    <li><a href="@Href("~/Contact.cshtml")">Contact</a></li>
</ul>

Elsewhere on SO I found quest开发者_开发技巧ions similar to mine, where people wanted to track the selected menu item, but within a dynamic page. For example:

Javascript Changing the selected Menu items class

But this approach won't work in my case because in my case the user is not changing a selection on one page, but navigating to another page completely.

How can this be done?


...and I figured it out.

I used Razor to implement this on the server side.

First I implemented a function on my _SiteLayout.cshtml page (the template all pages use):

@functions {
    public string Selected(string PageTitle) {
       if (Page.Title == PageTitle)
          return "selected";
        else
          return "";
    }
}

Then I used this function in my list:

<ul id="menu">
    <li class="@Selected("Home")"><a href="@Href("~/")">Home</a></li>
    <li class="@Selected("cek.log")"><a href="http://ceklog.kindel.com">cek.log</a></li>
    <li class="@Selected("Services")"><a href="@Href("~/Services")">Services</a></li>
    <li class="@Selected("Charlie's Stuff")"><a href="@Href("~/Charlie")">Charlie's Stuff</a></li>
    <li class="@Selected("Contact")"><a href="@Href("~/Contact.cshtml")">Contact</a></li>
</ul>

Works perfectly. On my external page, I just hand-coded it since it's based on Wordpress and not Razor.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号