首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

動態控件模擬複合控件(二):泛型數值輸入框與驗證邏輯封裝

     編輯:關於ASP.NET

泛型基類 NumberTextBox<T>

繼承 BaseTextBox,針對數值型別 實作範圍驗證:

public abstract class NumberTextBox : BaseTextBox where T : IComparable
{
    public virtual T MinValue { get; set; } = default(T);
    public virtual T MaxValue { get; set; } = default(T);
    protected abstract T DefaultMinValue { get; }
    protected abstract T DefaultMaxValue { get; }
    public virtual ValidationDataType Type { get; set; }

    public NumberTextBox()
    {
        this.FilterType = FilterTypes.Numbers;
        this.Options = TextBoxOptions.Required | TextBoxOptions.Filtered;
        this.MaxValue = this.DefaultMaxValue;
        this.MinValue = this.DefaultMinValue;
    }

    protected override void BuildValidatorControls()
    {
        base.BuildValidatorControls();
        // 根據 Min/Max 是否異於預設值,動態添加 RangeValidator 或 CompareValidator
        if (MinValueChanged && MaxValueChanged)
            AddRangeValidator();
        else if (MinValueChanged)
            AddMinCompareValidator();
        else if (MaxValueChanged)
            AddMaxCompareValidator();
    }
    // 驗證控件建立邏輯省略...
}

具體實作類別

public class IntNumberTextBox : NumberTextBox
{
    public IntNumberTextBox() { this.Type = ValidationDataType.Integer; }
    protected override int DefaultMinValue => int.MinValue;
    protected override int DefaultMaxValue => int.MaxValue;
}

public class MoneyTextBox : NumberTextBox
{
    public MoneyTextBox() { this.Type = ValidationDataType.Currency; }
    protected override decimal DefaultMinValue => decimal.MinValue;
    protected override decimal DefaultMaxValue => decimal.MaxValue;
}

設計優勢

  • 泛型約束:where T : IComparable<T> 確保型別可比較。
  • 驗證自動化:屬性變更自動生成對應驗證控件,無需手工拖放。
  • 擴展性:新增型別只需繼承並實作預設值,符合開放封閉原則。

此模式將「輸入過濾、必填驗證、範圍驗證」封裝於控件內部,頁面使用極簡潔:<custom:MoneyTextBox MinValue="0" MaxValue="10000" />。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved