根据控件的属性查找控件的子元素?

时间:2011-11-08 16:12:43

标签: c# asp.net

我想为我的网站制作一个导航栏。这个熊将有各种页面链接,并且应突出显示用户当前所在页面的链接。

目前我有这样的HTML:

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

我的PageLoad事件中的代码如下:

//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语句中。我想要一个更灵活的系统,我可以在其中动态添加链接到导航栏,并在用户位于右页时突出显示它们。

我该怎么做?是否可以根据navbar属性搜索href子元素?如果这些元素不必具有runat="server"属性,那么最好将它们视为常规HTML。或者我应该考虑采用不同的实现方式吗?

1 个答案:

答案 0 :(得分:1)

我遇到过很多需要寻找后代或祖先的情况。为此,我写了一些扩展方法,帮助我解决了很多问题。我建议使用以下代码:

需要使用声明:

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");