ASP.NET MVC菜单中选择项目 [英] ASP.NET MVC Menu Selected Item

查看:126
本文介绍了ASP.NET MVC菜单中选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定新的MVC。我曾问<一个href=\"http://stackoverflow.com/questions/4647135/asp-net-mvc-sitemap-and-or-security-trimming\">this质询时,得到一个答案,但我想知道如果有一个简单的解决方案。

说我有一个布局为一个无序列表菜单中的母版页。我怎么会去上当前选择的菜单项设置一个CSS类?

编辑:

我使用只是因为它来设置开箱当你开始一个新的MVC应用程序菜单

 &LT; UL ID =菜单&GT;
   &LT;立GT;&LT;%:Html.ActionLink(家,索引,家)%GT;&LT; /李&GT;
   &LT;立GT;&LT;%:Html.ActionLink(关于,关​​于,家)%GT;&LT; /李&GT;
&LT; / UL&GT;


解决方案

这的Jakub Konecki答案使我在正确的方向...这里是控制器动作我结束了:

  [ChildActionOnly]
    公众的ActionResult的MainMenu()
    {
        VAR项目=新的List&LT;&菜单项GT;
        {
            新菜单项的{text =家,行动=索引,控制器=家,选择= FALSE},
            新菜单项的{text =我的档案,行动=索引,控制器=档案,选择= FALSE},
            新菜单项的{text =关于,行动=关于,控制器=家,选择= FALSE}
        };        串动= ControllerContext.ParentActionViewContext.RouteData.Values​​ [行动]的ToString()。
        。字符串控制器= ControllerContext.ParentActionViewContext.RouteData.Values​​ [控制器]的ToString();        的foreach(在项目VAR项)
        {
            如果(item.Controller ==控制器和放大器;&安培; item.Action ==操作)
            {
                item.Selected = TRUE;
            }
        }        返回PartialView(项目);
    }

希望这可以帮助别人。

OK new to MVC. I had asked this question earlier and got an answer but I am wondering if there is a simpler solution.

Say I have a master page with a menu laid out as an unordered list. How would I go about setting a css class on the currently selected menu item?

EDIT:

I am using the menu just as it comes setup out of the box when you start a new mvc app

<ul id="menu">              
   <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
   <li><%: Html.ActionLink("About", "About", "Home")%></li>
</ul>

解决方案

The answer from Jakub Konecki led me in the right direction... here is the controller action I ended up with:

    [ChildActionOnly]
    public ActionResult MainMenu()
    {
        var items = new List<MenuItem>
        {
            new MenuItem{ Text = "Home", Action = "Index", Controller = "Home", Selected=false },
            new MenuItem{ Text = "My Profile", Action = "Index", Controller = "Profile", Selected = false},
            new MenuItem{ Text = "About", Action = "About", Controller = "Home", Selected = false }
        };

        string action = ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString();
        string controller = ControllerContext.ParentActionViewContext.RouteData.Values["controller"].ToString();

        foreach (var item in items)
        {
            if (item.Controller == controller && item.Action == action)
            {
                item.Selected = true;
            }
        }

        return PartialView(items);
    }

Hope this helps someone.

这篇关于ASP.NET MVC菜单中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆