2

選択したコントローラに応じてclass="active"を配置する方法は?<li>

<li  ><a href="@Url.Action("index", "Home")">Home</a></li>
<li  ><a href="@Url.Action("index", "Car")">Cars</a></li>

祝福

4

1 に答える 1

1

私は通常、このタスクを達成するためのアクション リンク HTML ヘルパーを作成します。リスト項目ではなく、リンク自体を「選択済み」としてマークしていることに注意してください。

public static class ActionLinkHelpers
{
    public static MvcHtmlString SelectedActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName)
    {
        var controller = (string) helper.ViewContext.RouteData.Values["controller"];
        if (string.Compare(controller, controllerName, StringComparison.InvariantCultureIgnoreCase) == 0)
        {
            return helper.ActionLink(linkText, actionName, controllerName, null, new { Class = "selected" }); 
        }

        return helper.ActionLink(linkText, actionName, controllerName);
    }
}

プロジェクト内にアクション リンク ヘルパーをセットアップすると、リストは次のようになります。

<li>@Html.SelectedActionLink("Home", "index", "Home")</li>
<li>@Html.SelectedActionLink("Cars", "index", "Car")</li>

編集:

カスタム ヘルパーを使用するには、MVC がそれを認識している必要があります。たとえば、プロジェクト「HtmlHelpers」に新しいフォルダーを追加し、このクラスをその中に配置します。そこから、次の行を追加する必要があります/Views/Web.config

<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="YourNameSpace.HtmlHelpers"/>
  </namespaces>
</pages>
于 2012-06-07T03:57:36.497 に答える