Trong một dự án gần đây của tôi, tôi đã làm điều đó bằng cách sử dụng phần mở rộng HtmlHelper và nhận dữ liệu từ bộ sưu tập ViewContext.RouteData.Values.
Vì vậy, xây dựng ra một phần mở rộng đơn giản như thế này:
public static string OnClass(this HtmlHelper html, bool isOn)
{
if (isOn)
return " class=\"on\"";
return string.Empty;
}
Bạn có thể xây dựng bất kỳ số lượng kết hợp, ví dụ
Chỉ cần kiểm tra các hành động hiện tại:
public static string OnClass(this HtmlHelper html, string action)
{
string currentAction = html.ViewContext.RouteData.Values["action"].ToString();
return html.OnClass(currentAction.ToLower() == action.ToLower());
}
kiểm tra đối với một số hành động:
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 cho hành động và điều khiển:
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;
}
Etc vv
Sau đó, bạn chỉ cần gọi nó trong (các) chế độ xem của bạn như vậy
<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>
Bạn đã bao giờ nhìn vào nó, phần mở rộng HtmlHelper là bạn của bạn! :-)
HTHs
Charles
liên quan: http://stackoverflow.com/questions/906423/jquery-add-class-on-current-item –
@Robert - Loại, nhưng tôi muốn có một giải pháp không phải javascript. Tôi sẽ nghĩ lý tưởng, vì tôi có tất cả thông tin tôi cần trên máy chủ, tôi có thể thực hiện điều này trên máy chủ. – Martin