2011-11-08 2 views
4

내 웹 사이트의 탐색 바를 만들고 싶습니다. 이 곰은 페이지에 대한 다양한 링크를 가지며 사용자가 현재 연결되어있는 페이지에 대한 링크를 강조 표시해야합니다. 나는이 같은 HTML이 순간해당 특성을 기반으로 컨트롤의 하위 요소를 찾으십시오.

:이처럼 내 PageLoad 이벤트

<div id="navbar" runat="server"> 
    <a href="/" runat="server" id="lnkHome">Home</a> | 
    <a href="~/info.aspx" runat="server" id="lnkInfo">Info</a> | 
    <a href="~/contacts.aspx" runat="server" id="lnkContacts">Contacts</a> | 
    <a href="~/settings.aspx" runat="server" id="lnkSettings">Settings</a> 
</div> 

그리고 코드 :

//Show the currently selected page 
String filename = System.IO.Path.GetFileNameWithoutExtension(Request.Path).ToLower(); 
if (filename == "default") 
    lnkHome.Attributes.Add("class", "selected"); 
else if (filename == "info") 
    lnkInfo.Attributes.Add("class", "selected"); 
else if (filename == "contacts") 
    lnkContacts.Attributes.Add("class", "selected"); 
else if (filename == "settings") 
    lnkSettings.Attributes.Add("class","selected"); 

이 유지하기 어렵다. 링크를 추가하려면 ID를 부여하고 if 문에 정보를 추가해야합니다. 좀 더 유연한 시스템이 필요합니다. 여기서 동적으로 탐색 바에 링크를 추가 할 수 있으며 사용자가 올바른 페이지에있을 때 강조 표시되도록 할 수 있습니다.

어떻게하면됩니까? href 속성을 기반으로 하위 요소에 대해 navbar을 검색 할 수 있습니까? 이러한 요소가 runat="server" 특성을 가질 필요가 없으므로 최상의 것이므로 정규 HTML과 마찬가지로 처리 할 수 ​​있습니다. 아니면 고려해야 할 다른 구현이 있습니까?

답변

1

필자는 후손이나 조상을 찾아야하는 경우가 많았습니다. 이에 대응하기 위해 필자는 많은 도움이되는 확장 방법을 작성했습니다.

필수 using 문 :

using System.Collections.Generic; 
using System.Web.UI; 

확장 방법 :

/// <summary> 
/// Finds a single, strongly-typed descendant control by its ID. 
/// </summary> 
/// <typeparam name="T">The type of the descendant control to find.</typeparam> 
/// <param name="control">The root control to start the search in.</param> 
/// <param name="id">The ID of the control to find.</param> 
/// <returns>Returns a control which matches the ID and type passed in.</returns> 
public static T FindDescendantById<T>(this Control control, string id) where T : Control 
{ 
    return FindDescendantByIdRecursive<T>(control, id); 
} 

/// <summary> 
/// Recursive helper method which finds a single, strongly-typed descendant control by its ID. 
/// </summary> 
/// <typeparam name="T">The type of the descendant control to find.</typeparam> 
/// <param name="root">The root control to start the search in.</param> 
/// <param name="id">The ID of the control to find.</param> 
/// <returns>Returns a control which matches the ID and type passed in.</returns> 
private static T FindDescendantByIdRecursive<T>(this Control root, string id) where T : Control 
{ 
    if (root is T && root.ID.ToLower() == id.ToLower()) 
    { 
     return (T)root; 
    } 
    else 
    { 
     foreach (Control child in root.Controls) 
     { 
      T target = FindDescendantByIdRecursive<T>(child, id); 
      if (target != null) 
      { 
       return target; 
      } 
     } 

     return null; 
    } 
} 

귀하의 C# 코드 숨김

var fileName = Path.GetFileNameWithoutExtension(Request.Path); 
var controlId = "lnk" + fileName; 
var anchorTag = navbar.FindDescendantById<HtmlAnchor>(controlId); 
anchorTag.Attributes.Add("class", "selected"); 
를 다음 코드와 다음을 사용하는 것이 좋습니다 것입니다
관련 문제