ASP.NET MVC - 基于控制器的样式列表项 [英] ASP.NET MVC - style list item based on controller

查看:70
本文介绍了ASP.NET MVC - 基于控制器的样式列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的最终目标是拥有,增加了一个类,与当前页面的同事,我的列表项的菜单。

My ultimate goal is to have a menu that adds a class to the list item that associates with the current page I am on.

所以,我有它设置,使每个控制器将与我的菜单项关联。我需要一个类添加到列表项(改变颜色,背景,等等)。

So I have it set up such that each controller will be associated with an item in my menu. I need to add a class to that list item (changing the color, background, whatever).

有没有一种简单的方法来做到这一点?值传递给视图,然后呢?

Is there a simple way to do this? Pass a value to the View, then what?

推荐答案

在我最近的项目,我做到了使用的HtmlHelper扩展,并从ViewContext.RouteData.Values​​集合中获取数据。

In a recent project of mine I did it using HtmlHelper extensions and getting data from the ViewContext.RouteData.Values collection.

所以建立了一个简单的扩展是这样的:

So building off a simple extension like this:

public static string OnClass(this HtmlHelper html, bool isOn)
{
    if (isOn)
        return " class=\"on\"";

    return string.Empty;
}

您可以建立任何数量的组合,例如

You can build up any number of combinations, e.g.

只是测试当前的动作:

public static string OnClass(this HtmlHelper html, string action)
{
    string currentAction = html.ViewContext.RouteData.Values["action"].ToString();

    return html.OnClass(currentAction.ToLower() == action.ToLower());
}

测试了一系列行动:

Testing for a number of actions:

public static string OnClass(this HtmlHelper html, string[] actions)
{
    string currentAction = html.ViewContext.RouteData.Values["action"].ToString();

    foreach (string action in actions)
    {
        if (currentAction.ToLower() == action.ToLower())
            return html.OnClass(true);
    }

    return string.Empty;
}

测试行动和控制器:

Testing for action and controller:

public static string OnClass(this HtmlHelper html, string action, string controller)
{
    string currentController = html.ViewContext.RouteData.Values["controller"].ToString();

    if (currentController.ToLower() == controller.ToLower())
        return html.OnClass(action);

    return string.Empty;
}

等等,等等。

然后你只需调用它在你的视图(S),像这样

Then you simply call it in your view(s) like so

<ul id="left-menu">
    <!-- simple boolean -->
    <li <%= Html.OnClass(something == somethingElse) %>>Blah</li>
    <!-- action -->
    <li <%= Html.OnClass("Index") %>>Blah</li>
    <!-- any number of actions -->
    <li <%= Html.OnClass(new string[] { "Index", "Details", "View" }) %>>Blah</li>
    <!-- action and controller -->
    <li <%= Html.OnClass("Index", "Home") %>>Blah</li>
</ul>

以往的方式你看哪个吧,扩展的HtmlHelper是你的朋友! : - )

Which ever way you look at it, HtmlHelper extensions are your friend! :-)



查尔斯

HTHs
Charles

这篇关于ASP.NET MVC - 基于控制器的样式列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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