C#选择具有特定CssClass的所有文本框

本文关键字:文本 CssClass 选择 | 更新日期: 2023-09-27 18:28:09

我想进行服务器端验证,以确保类为"required"的每个文本框都不是空的。我可以在jQuery中做到这一点,没有问题,但还不是C#的专业人员。我得到的是:

protected void BtnCatering_Click(object sender, EventArgs e)
{
    if (TextBox.CssClass == "required" && TextBox.Text == "")
    {
        MessageBox.Show("Please fill in required fields");
    }
}
<p>
    <label for="BookingName">Booking Name <span>*</span></label>
    <asp:TextBox class="inputText required" ID="BookingName" runat="server" />
</p>
<p>
    <label for="ArrivaltDate">Arrival Date<span>*</span></label>
    <asp:TextBox CssClass="myDatepicker inputText required" id="ArrivaltDate" runat="server" />
</p

C#选择具有特定CssClass的所有文本框

类似的东西可能是您的解决方案:

var results = this.Controls.OfType<TextBox>().Where(c =>
    Convert.ToString(c.Attributes["class"]).Contains("required"));

然后您可以对结果集进行迭代。可能是这样的:

foreach (var tb in results)
{
    if (string.IsNullOrEmpty(tb.Text))
    {
        // do something here because this TextBox is empty
    }
}

然而,更正确的方法可能是对每个控件使用RequiredFieldValidator,这样您就可以在准备好时在Page上调用this.Validate(),然后在Page上检查this.IsValid并对其做出反应。

试试这种方法。

protected void BtnCatering_Click(object sender, EventArgs e)
{
    if (BookingName.Attributes["class"].ToString().Contains("required") && BookingName.Text == "")
    {
        MessageBox.Show("Please fill in required fields");
    }
}

//BookingName是您的文本框id。

因此,ASP.NET具有Validation Controls,您可以使用它在服务器端验证数据(也可以选择在客户端验证数据)。

您可以对每个文本框使用RequiredFieldValidator控件,也可以使用CustomValidator控件。

请参阅MSDN:ASP.NET服务器控件的验证类型。

例如,对于ID为BookingNameTextBox控件,可以使用以下内容。

<asp:RequiredFieldValidator EnableClientScript="False" ID="RequiredFieldValidator1" ControlToValidate="BookingName" runat="server" ErrorMessage="Please fill in this field"></asp:RequiredFieldValidator>

如果您正在使用Visual Studio,这些控件就在您的工具箱中。

代码简单如下:

if (CssUtils.HasClass(TextBox.CssClass, "required") && TextBox.Text == "") {
    ..do stuff..
}

但这当然是假设您有一个有效的CssUtils类,它可以准确地检测类的存在。

public static class CssUtils
{
    /// <summary>
    /// http://dev.w3.org/html5/spec/common-microsyntaxes.html#space-character
    /// </summary>
    private static readonly char[] WhitespaceCharacters = new[] { ' ', ''t', ''n', ''f', ''r' };
    /// <summary>
    /// ToggleAggregator toggles the <paramref name="parsedClass"/> within the <paramref name="current"/> classes.
    /// </summary>
    /// <param name="current">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="parsedClass">
    /// A class to toggle within the <paramref name="current"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of resultant classes.
    /// </returns>
    private static string ToggleAggregator(string current, string parsedClass)
    {
        return HasClass(current, parsedClass)
                   ? RemoveClass(current, parsedClass)
                   : AddClass(current, parsedClass);
    }
    /// <summary>
    /// AddClass adds the provided <paramref name="classes"/> to the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to add to the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of merged classes.
    /// </returns>
    public static string AddClass(string source, string classes)
    {
        var sourceClasses = ParseClasses(source);
        var parsedClasses = ParseClasses(classes);
        var mergedClasses =
            sourceClasses
                .Union(parsedClasses)
                .ToArray()
                .Join(" ");
        return mergedClasses;
    }
    /// <summary>
    /// AddClass adds the provided <paramref name="classes"/> to the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// An <see cref="Array.string"/> of classes to add to the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of merged classes.
    /// </returns>
    public static string AddClass(string source, params string[] classes)
    {
        return AddClass(source, classes.Join(" "));
    }
    /// <summary>
    /// HasClass checks whether all of the provided <paramref name="classes"/> are contained in the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to check in the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// <c>True</c> if all of the <paramref name="classes"/> are contained in the <paramref name="source"/> classes, <c>False</c> otherwise.
    /// </returns>
    public static bool HasClass(string source, string classes)
    {
        if (source.IsEmpty() || classes.IsEmpty()) return false;
        var sourceClasses = ParseClasses(source);
        var parsedClasses = ParseClasses(classes);
        return parsedClasses.Intersect(sourceClasses).Count() == parsedClasses.Count();
    }
    /// <summary>
    /// RemoveClass removes the provided <paramref name="classes"/> from the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to remove from the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of remaining classes.
    /// </returns>
    public static string RemoveClass(string source, string classes)
    {
        var sourceClasses = ParseClasses(source);
        var parsedClasses = ParseClasses(classes);
        var resultClasses =
            sourceClasses
                .Except(parsedClasses)
                .ToArray()
                .Join(" ");
        return resultClasses;
    }
    /// <summary>
    /// RemoveClass removes the provided <paramref name="classes"/> from the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// An <see cref="Array.string"/> of classes to remove from the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of remaining classes.
    /// </returns>
    public static string RemoveClass(string source, params string[] classes)
    {
        return RemoveClass(source, classes.Join(" "));
    }
    /// <summary>
    /// ToggleClass toggles the provided <paramref name="classes"/> within the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to toggle within the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of resultant classes.
    /// </returns>
    public static string ToggleClass(string source, string classes)
    {
        var parsedClasses = ParseClasses(classes);
        return parsedClasses.Aggregate(source ?? "", ToggleAggregator);
    }
    /// <summary>
    /// ToggleClass toggles the provided <paramref name="classes"/> within the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// An <see cref="Array.string"/> of classes to toggle within the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of resultant classes.
    /// </returns>
    public static string ToggleClass(string source, params string[] classes)
    {
        return ToggleClass(source, classes.Join(" "));
    }
    /// <summary>
    /// ToggleClass toggles the provided <paramref name="classes"/> within the <paramref name="source"/> classes dependant on the state of the <paramref name="switch"/>.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to toggle within the <paramref name="source"/> classes.
    /// </param>
    /// <param name="switch">
    /// When <c>True</c>, the <paramref name="classes"/> will be added to the <paramref name="source"/> classes.
    /// When <c>False</c>, the <paramref name="classes"/> will be removed from the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of resultant classes.
    /// </returns>
    public static string ToggleClass(string source, string classes, bool @switch)
    {
        return @switch ? AddClass(source, classes) : RemoveClass(source, classes);
    }
    /// <summary>
    /// ParseClasses splits the provided whitespace separated list of <paramref name="classes"/> into an array of distinct classes.
    /// </summary>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <returns>
    /// A <see cref="Array.string"/> of distinct classes.
    /// </returns>
    public static string[] ParseClasses(string classes)
    {
        return (classes ?? "")
            .Split(WhitespaceCharacters, StringSplitOptions.RemoveEmptyEntries)
            .Distinct()
            .ToArray();
    }
}