微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

我该怎么做呢?是否可以根据其href属性在navbar中搜索子元素?如果这些元素不必具有runat =“server”属性,那么最好将它们视为常规HTML.或者我应该考虑不同的实现?

解决方法

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

使用声明必需:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐