활성 메뉴 항목-asp.net mvc3 마스터 페이지
마스터 페이지의 메뉴 항목에 "활성 / 현재"클래스를 할당하기위한 적절한 솔루션을 찾으려고 노력하고 있습니다. 이 행은이 클라이언트 대 서버 측을 수행할지 여부와 관련하여 중간으로 나뉩니다.
솔직히 저는 JavaScript와 MVC를 처음 사용하므로 의견이 없습니다. 나는 이것을 "가장 깨끗하고"가장 적절한 방법으로하는 것을 선호한다.
<li> 항목에 "활성"클래스를 할당하는 다음 jQuery 코드가 있습니다. 유일한 문제는 URL이 항상 하위 문자열이기 때문에 "인덱스"또는 기본보기 메뉴 항목이 항상 활성 클래스에 할당된다는 것입니다. 다른 메뉴 링크 :
(default) index = localhost/
link 1 = localhost/home/link1
link 2 = localhost/home/link1
$(function () {
var str = location.href.toLowerCase();
$('#nav ul li a').each(function() {
if (str.indexOf(this.href.toLowerCase()) > -1) {
$(this).parent().attr("class","active"); //hightlight parent tab
}
});
더 나은 방법이 있나요? 누군가가 클라이언트 측 버전의 방탄을 얻을 수 있도록 도와 주겠습니까? 그러면 "인덱스"또는 기본 링크가 항상 "활성"상태입니까? 인덱스 메서드에 가짜 확장을 할당하는 방법이 있습니까? 기본 URL 대신 localhost/home/dashboard
모든 링크의 하위 문자열이되지 않도록하는 것과 같습니다.
솔직히, 나는이 서버 측을 수행하는 방법을 실제로 따르지 않습니다. 그래서 jQuery로 클라이언트 측을 시도하고 있습니다 ... 어떤 도움을 주시면 감사하겠습니다.
사용자 정의 HTML 도우미는 일반적으로 작업을 잘 수행합니다.
public static MvcHtmlString MenuLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName
)
{
string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
if (actionName == currentAction && controllerName == currentController)
{
return htmlHelper.ActionLink(
linkText,
actionName,
controllerName,
null,
new {
@class = "current"
});
}
return htmlHelper.ActionLink(linkText, actionName, controllerName);
}
마스터 페이지에서 :
<ul>
<li>@Html.MenuLink("Link 1", "link1", "Home")</li>
<li>@Html.MenuLink("Link 2", "link2", "Home")</li>
</ul>
이제 남은 것은 .current CSS 클래스를 정의하는 것입니다.
영역에 대한 추가 지원 :
public static class MenuExtensions
{
public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper, string text, string action, string controller, string area = null)
{
var li = new TagBuilder("li");
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
var currentArea = routeData.DataTokens["area"] as string;
if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentArea, area, StringComparison.OrdinalIgnoreCase))
{
li.AddCssClass("active");
}
li.InnerHtml = htmlHelper.ActionLink(text, action, controller, new {area}, null).ToHtmlString();
return MvcHtmlString.Create(li.ToString());
}
}
이 문제에 대한 해결책은 다음과 같습니다.
HtmlHelpers 클래스의 다음 확장 메서드를 만들었습니다.
public static class HtmlHelpers
{
public static string SetMenuItemClass(this HtmlHelper helper, string actionName)
{
if (actionName == helper.ViewContext.RouteData.Values["action"].ToString())
return "menu_on";
else
return "menu_off";
}
그런 다음 내 메뉴 블록이 있습니다. 다음과 같이 보입니다.
<div id="MenuBlock">
<div class="@Html.SetMenuItemClass("About")">
<a>@Html.ActionLink("About", "About", "Home")</a></div>
<img height="31" width="2" class="line" alt="|" src="@Url.Content("~/Content/theme/images/menu_line.gif")"/>
<div class="@Html.SetMenuItemClass("Prices")">
<a>@Html.ActionLink("Prices", "Prices", "Home")</a></div>
</div>
So my method returns class name to every div according to current action of Home controller. You can go deeper and add to the method one parameter, which specifies the name of the controller to avoid problems, when you have actions with the same name but of different controllers.
Through JQuery u can do like this:
$(document).ready(function () {
highlightActiveMenuItem();
});
highlightActiveMenuItem = function () {
var url = window.location.pathname;
$('.menu a[href="' + url + '"]').addClass('active_menu_item');
};
.active_menu_item {
color: #000 !important;
font-weight: bold !important;
}
Original: http://www.paulund.co.uk/use-jquery-to-highlight-active-menu-item
What I usually do is assign a class to the body tag that's based on the path parts. So like, if you do a String.Replace on the path to turn /blogs/posts/1 to class="blogs posts 1".
Then, you can assign CSS rules to handle that. For example, if you have a menu item for "blogs", you can just do a rule like
BODY.blogs li.blogs { /* your style */}
or if you want a particular style if your on a post only vice if you're on the blog root page
BODY.blogs.posts li.blogs {/* your style */}
참고URL : https://stackoverflow.com/questions/4728777/active-menu-item-asp-net-mvc3-master-page
'Development Tip' 카테고리의 다른 글
SQL LIKE 절에서 SqlParameter 사용이 작동하지 않음 (0) | 2020.11.17 |
---|---|
MVC 대 3 계층 아키텍처? (0) | 2020.11.17 |
Google C ++ 스타일 가이드의 예외 없음 규칙; (0) | 2020.11.17 |
생성자에서 C ++ 개체 멤버 변수를 초기화하려면 어떻게해야합니까? (0) | 2020.11.17 |
matplotlib에 선 스타일 목록이 있습니까? (0) | 2020.11.17 |