【问题标题】:Apply CSS class to invalid controls on web form将 CSS 类应用于 Web 表单上的无效控件
【发布时间】:2011-03-05 04:33:41
【问题描述】:

我需要将 CSS 类应用于 Web 表单上的无效控件。我想让它成为一个可重复使用的类。这是我目前所拥有的:

public class Validation
{
    public static void ApplyInvalidClass(Page page, string className)
    {
        foreach (System.Web.UI.WebControls.BaseValidator bv in page.Validators)
        {
            if (!bv.IsValid)
            {
                Control ctrl = page.FindControl(bv.ControlToValidate);

                if (ctrl != null)
                {
                    if (ctrl is TextBox)
                    {
                        TextBox txt = ctrl as TextBox;
                        txt.CssClass = "invalid";
                    }

                    if (ctrl is DropDownList)
                    {
                        DropDownList ddl = ctrl as DropDownList;
                        ddl.CssClass = "invalid";
                    }

                    if (ctrl is CheckBox)
                    {
                        CheckBox cb = ctrl as CheckBox;
                        cb.CssClass = "invalid";
                    }

                    if (ctrl is HtmlGenericControl)
                    {
                        HtmlGenericControl html = ctrl as HtmlGenericControl;
                        html.Attributes.Add("class", className);
                    }
                }
            }
        }
    }

}

问题是我在 .Net 用户控件上调用它,我猜是因为我正在传递 Page,page.FindControl(bv.ControlToValidate) 始终为空。

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: asp.net webforms


    【解决方案1】:

    Page.FindControl 不是递归的,它只搜索控件集合中的直接内容。因为您要搜索的控件嵌套在 UserControl 中,所以它会显示为 null。

    你可以看到recursive FindControl function here的一个版本。

    【讨论】:

    • 我认为正确的行为需要使用 validator.NamingContainer.FindControl(...) 而不是 page.FindControl(...) 来解决。一个页面中可能有多个同名控件。
    猜你喜欢
    • 2014-08-18
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2012-10-28
    相关资源
    最近更新 更多