2009-08-05 6 views
8

나의 궁극적 인 목표는 현재 페이지와 연관된 목록 항목에 클래스를 추가하는 메뉴를 만드는 것입니다.컨트롤러를 기반으로하는 ASP.NET MVC 스타일 목록 항목

그래서 각 컨트롤러가 내 메뉴의 항목과 연결되도록 설정했습니다. 해당 목록 항목에 클래스를 추가해야합니다 (색상, 배경 등을 변경).

간단한 방법이 있나요? 보기에 값을 전달한 다음 무엇을?

+0

관련 : http://stackoverflow.com/questions/906423/jquery-add-class-on-current-item –

+0

@Robert - 종류의,하지만 내가 원하는 비 자바 스크립트 솔루션. 서버에 필요한 정보가 모두 있기 때문에 이상적으로 생각합니다. 서버에서이 작업을 수행 할 수 있습니다. – Martin

답변

12

최근의 프로젝트에서는 HtmlHelper 확장을 사용하고 ViewContext.RouteData.Values ​​컬렉션에서 데이터를 가져 왔습니다.

그래서 다음과 같이 간단한 확장을 구축 :

public static string OnClass(this HtmlHelper html, bool isOn) 
{ 
    if (isOn) 
     return " class=\"on\""; 

    return string.Empty; 
} 

당신은 조합의 수를 구축 할 수 있습니다, 예를

그냥 현재의 액션 테스트 : 행동과 컨트롤러에 대한

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; 
} 

테스트 : 행동의 번호

public static string OnClass(this HtmlHelper html, string action) 
{ 
    string currentAction = html.ViewContext.RouteData.Values["action"].ToString(); 

    return html.OnClass(currentAction.ToLower() == action.ToLower()); 
} 

테스트를

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; 
} 

기타 등

그럼 당신은 단순히 적 방법으로 당신이 그것을 보면

<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> 

그래서

처럼보기 (들)에 전화, Html 헬퍼 확장 당신의 친구입니다! :-)

HTHs
찰스

+0

나는 이것을보고 그것을 구현할 수있는 기회를 얻었습니다. 멋지다! 고마워 친구! – Martin

+1

if (currentAction.ToLower() == action.ToLower()) .. 문자열을 비교하는 적절한 방법은 StringComparison.InvariantCultureIgnoreCase를 사용하는 것입니다. –

관련 문제