1

私はMVC4アプリケーションに取り組んでいます

次のメニュー項目があります

<ul class="menu left">
                <li>@Html.ActionLink("Home", "Index", new { Controller = "Home" }, new { @class = "active" })</li>
                <li>@Html.ActionLink("About Us", "About", new { Controller = "Home" })</li>
                <li>@Html.ActionLink("Services", "Services", new { Controller = "Home" })</li>      
                <li>@Html.ActionLink("Post Job", "Create", new { Controller = "JobPosting" })</li>
                <li>@Html.ActionLink("Job Search", "Index", new { Controller = "JobPosting" })</li>
                <li>@Html.ActionLink("Contact Us", "Contact", new { Controller = "Home" })</li>
           </ul>

ホーム以外のアイテムをクリックすると、css-class がアクティブに変わります。基本的に、メニュー項目の色を変更したいだけですどうすれば動的にできますか?

4

2 に答える 2

3

アクションまたはコントローラーに基づいてcssを変更する場合は、使用できます

@{
    var controller = ViewContext.RouteData.Values["Controller"].ToString();
    var action = ViewContext.RouteData.Values["Action"].ToString();
}

<li> 
    @if (action == "Home") { 
       @Html.ActionLink("Home", "Index", new { Controller = "Home" },new {@class="active" })
    }
    else {
       @Html.ActionLink("Home", "Index", new { Controller = "Home" })
    }
</li>
<li>
   @if (action == "About Us") { 
           @Html.ActionLink("About Us", "About", new { Controller = "Home" },new {@class="active" })
        }
        else {
           @Html.ActionLink("About Us", "About", new { Controller = "Home" })
        }
</li>

等...

于 2013-02-08T11:28:26.877 に答える
0
public static class MyHtmlHelper
{
    public static String NavActive(this HtmlHelper htmlHelper, 
                          string actionName, 
                          string controllerName)
    {
        var controller = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
        var action = htmlHelper.ViewContext.RouteData.GetRequiredString("action");

        if (controllerName == controller && action == actionName )
            return "active";
        else
            return String.Empty;
    }
}

次に、ビューでこのヘルパーを使用できます。

@Html.NavActive("Index", "Home")

例えば、

<li>
    <a href="~/Home/Index" class="@Html.NavActive("Index", "Home")">
        <span>Index</span>
    </a>
</li>
于 2013-02-08T11:38:52.737 に答える