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

ASP.NET 利用 XML 設定檔動態控制輸入長度與提示訊息

     編輯:關於C#

需求場景

企業級 Web 系統常需依頁面、角色或業務規則動態調整文字方塊的最大長度、水印提示與錯誤訊息。硬編碼在頁面不利維護,採用 XML 組態 + 通用類別 可實現「不改程式碼、只改設定檔」即時生效。

XML 結構設計

<?xml version="1.0" encoding="utf-8"?>
<Tree>
  <Node>
    <Name>登入頁-內容輸入</Name>
    <PageId>Notice_Login_txtContent</PageId>
    <Control value="500"></Control>   <!-- 最大長度 -->
    <Message>請輸入登入公告內容,最多 500 字</Message> <!-- 水印/提示 -->
  </Node>
  <Node>
    <Name>註冊頁-暱稱</Name>
    <PageId>Register_txtNickName</PageId>
    <Control value="20"></Control>
    <Message>暱稱 2-20 字元</Message>
  </Node>
</Tree>

通用存取類別

using System;
using System.Xml;
using System.Configuration;
using System.Web.UI.WebControls;

namespace XMLSize
{
    /// 
    /// 回傳資料結構
    /// 
    public struct RestrictInfo
    {
        public string PromptMessage; // 提示/水印文字
        public string ErrorMessage;  // 驗證失敗訊息
        public int MaxLength;        // 最大長度
    }

    public static class XmlRestrict
    {
        /// 
        /// 依 XML 節點 ID 取得限制設定
        /// 
        /// web.config 中指向 XML 目錄的鍵值
        /// XML 中 PageId 值
        /// 找到回傳 RestrictInfo,否則回傳 null
        public static RestrictInfo? GetRestrict(string configKey, string nodeId)
        {
            string xmlPath = ConfigurationManager.AppSettings[configKey] + "Restrict.xml";
            var doc = new XmlDocument();
            try { doc.Load(xmlPath); }
            catch { return null; }

            foreach (XmlNode node in doc.SelectSingleNode("Tree").ChildNodes)
            {
                if (node.Name != "Node") continue;
                var pageIdNode = node.SelectSingleNode("PageId");
                if (pageIdNode?.InnerText == nodeId)
                {
                    int maxLen = 0;
                    int.TryParse(node.SelectSingleNode("Control")?.Attributes["value"]?.Value, out maxLen);
                    return new RestrictInfo
                    {
                        MaxLength = maxLen,
                        PromptMessage = node.SelectSingleNode("Message")?.InnerText ?? "",
                        ErrorMessage = $"輸入長度不可超過 {maxLen} 字元"
                    };
                }
            }
            return null;
        }

        /// 
        /// 一鍵套用至 TextBox 與 Label
        /// 
        public static void Apply(TextBox txt, Label lblPrompt, Label lblError, RestrictInfo info)
        {
            txt.MaxLength = info.MaxLength;
            lblPrompt.Text = info.PromptMessage;
            lblError.Text = info.ErrorMessage;
        }
    }
}

Web.config 設定

<appSettings>
  <add key="webPath" value="~/App_Data/Config/" />
</appSettings>

頁面套用範例

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var info = XmlRestrict.GetRestrict("webPath", "Notice_Login_txtContent");
        if (info.HasValue)
            XmlRestrict.Apply(txtContent, lblPrompt, lblError, info.Value);
    }
}

擴充建議

  • 快取機制:靜態 `Dictionary` 快取已讀取節點,避免每次請求讀檔。
  • 驗證整合:搭配 `CustomValidator` 在伺服端複核長度,防繞過前端限制。
  • 多語系:XML 節點加入 `lang` 屬性,依 `Thread.CurrentUICulture` 切換訊息。
  • 型別擴充:`Control` 節點增加 `type="number|date|regex"` 與 `pattern` 屬性,支援更豐富驗證。

總結

以 XML 為中心的設定模式,將「業務規則」與「程式邏輯」解耦,讓非技術人員也能透過修改文字檔即時調整前端行為,極大降低維護成本。搭配快取與驗證整合,即可構建彈性、安全的動態表單驗證框架。

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