我在mvc4中实现选项卡式视图。所以我实现了局部视图,它反过来在每个视图中调用标签式结构。以下代码根据从视图传递的参数设置活动选项卡。
<ul class="nav nav-tabs">
@{ var UserFocus = ""; var CardFocus = ""; var CarrierFocus = ""; }
@{
switch(ViewData["ActiveMenu"].ToString())
{
case "User":
UserFocus = "active";
break;
case "Card":
CardFocus = "active";
break;
case "Carrier":
CarrierFocus = "active";
break;
}
}
<li class="@UserFocus">User view link</li>
<li class="@CardFocus">card view link</li>
<li class="@CarrierFocus">Carrier view link</li>
</ul>
在每个视图中,它都会根据视图
调用@Html.Partial("_AdminSettings", new ViewDataDictionary {{ "ActiveMenu", "User" }} )
这很好用。
答案 0 :(得分:4)
就个人而言,我不喜欢视图中的逻辑。根据经验,我通常将逻辑放在模型中并将其传递给视图,并相信视图可以显示数据的外观,而不是操纵数据。
作为替代方法,您可以拥有Navigation Model
并传递:
ViewData["ActiveMenu"]
到您的控制器并填充Navigation Model
。
public class NavigationModel
{
public string UserFocus { get; private set; }
public string CardFocus { get; private set; }
public string CarrierFocus { get; private set; }
public NavigationModel(string ActiveMenu)
{
// Your switch statement to populate the properties.
}
}
您的观点如下所示:
@Model NavigationModel
<ul class="nav nav-tabs">
<li class="@Model.UserFocus">User view link</li>
<li class="@Model.CardFocus">card view link</li>
<li class="@Model.CarrierFocus">Carrier view link</li>
</ul>
在我看来哪个更干净。