萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 自訂彈出式日期選擇器使用者控制項

設計目標

  • 封裝 `TextBox` + `Button` + `Calendar` 為可重複使用的 `.ascx` 使用者控制項。
  • 點擊按鈕顯示/隱藏 Calendar,選取日期自動填入 TextBox 並關閉。
  • 支援同一頁多個實例 (ID 隔離)。
  • 純伺服器端渲染 + 少量 JavaScript,無外部依賴。

控制項標記 (.ascx)

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DatePicker.ascx.cs" Inherits="WebControls.DatePicker" %>
<asp:TextBox ID="txtDate" runat="server" Width="100px" />
<input type="button" id="btnToggle" runat="server" value="..." /><br />
<asp:Panel ID="pnlCalendar" runat="server" Style="position:absolute; display:none; z-index:1000;">
    <asp:Calendar ID="calDate" runat="server" 
        FirstDayOfWeek="Monday" 
        ShowGridLines="True" 
        BackColor="White" 
        Font-Size="8pt" Font-Names="Verdana"
        BorderColor="#999999" CellPadding="4" Width="200px" Height="180px">
        <TodayDayStyle ForeColor="Black" BackColor="#CCCCCC" />
        <SelectedDayStyle Font-Bold="True" ForeColor="White" BackColor="#666666" />
        <TitleStyle Font-Bold="True" BackColor="#999999" />
        <WeekendDayStyle BackColor="LightSteelBlue" />
    </asp:Calendar>
</asp:Panel>

代碼後置 (.ascx.cs)

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebControls
{
    public partial class DatePicker : UserControl
    {
        protected TextBox txtDate;
        protected Panel pnlCalendar;
        protected HtmlInputButton btnToggle;
        protected Calendar calDate;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtDate.Text = DateTime.Today.ToShortDateString();
                pnlCalendar.Attributes["style"] = "display:none; position:absolute;";
            }
            else
            {
                // 判斷 PostBack 來源:若非本控制項觸發,隱藏日曆
                string target = Request.Form["__EVENTTARGET"] ?? "";
                string myPrefix = this.ClientID + "_"; // 或 this.UniqueID + "$"
                if (!target.StartsWith(myPrefix))
                {
                    pnlCalendar.Attributes["style"] = "display:none; position:absolute;";
                }
                else
                {
                    pnlCalendar.Attributes["style"] = "position:absolute;";
                }
            }

            // 註冊客戶端切換腳本 (每個實例唯一函數名)
            string script = $@"
function {ClientID}_toggle() {{
    var p = document.getElementById('{pnlCalendar.ClientID}');
    p.style.display = (p.style.display === 'none') ? '' : 'none';
}}";
            ScriptManager.RegisterClientScriptBlock(this, GetType(), ClientID + "_toggle", script, true);

            // 綁定按鈕點擊
            btnToggle.Attributes["onclick"] = $"{ClientID}_toggle(); return false;";
        }

        protected void calDate_SelectionChanged(object sender, EventArgs e)
        {
            txtDate.Text = calDate.SelectedDate.ToShortDateString();
            pnlCalendar.Attributes["style"] = "display:none; position:absolute;";
        }

        // 對外屬性
        public string SelectedDateText
        {
            get => txtDate.Text;
            set => txtDate.Text = value;
        }

        public DateTime? SelectedDate
        {
            get => DateTime.TryParse(txtDate.Text, out var d) ? d : (DateTime?)null;
            set => txtDate.Text = value?.ToShortDateString() ?? "";
        }
    }
}

使用方式 (.aspx)

<%@ Register Src="~/Controls/DatePicker.ascx" TagPrefix="uc" TagName="DatePicker" %>
<html><body><form runat="server">
    開始日期:<uc:DatePicker ID="dpStart" runat="server" /><br/>
    結束日期:<uc:DatePicker ID="dpEnd" runat="server" /><br/>
    <asp:Button Text="送出" OnClick="btnSubmit_Click" runat="server" />
</form></body></html>
protected void btnSubmit_Click(object sender, EventArgs e)
{
    var start = dpStart.SelectedDate;
    var end = dpEnd.SelectedDate;
    // 業務邏輯...
}

現代化替代方案 (強烈建議)

方案優點整合方式
HTML5 <input type="date">零 JS、原生 UI、行動裝置友善、無相依``
jQuery UI Datepicker功能豐富、主題化、本地化NuGet `jQuery.UI.Combined` + `$("[id$=txtDate]").datepicker()`
Bootstrap Datepicker / Flatpickr輕量、無 jQuery 依賴、ESM 模組化CDN 引入 + JS 初始化
ASP.NET Core TagHelper伺服器端渲染、強型別、驗證整合``

常見問題與修正

  • UpdatePanel 部分更新後日曆失效:需在 `Page_Load` 每次重新註冊 Script (已在範例中處理)。
  • Calendar 顯示位置錯誤:確保 `Panel` 為 `position:absolute`,且無父層 `overflow:hidden` 遮擋。
  • 多實例 ID 衝突:使用 `ClientID` 產生唯一 JS 函數名與元素選取器 (範例已示範)。
  • 行動裝置彈出鍵盤遮擋:HTML5 `type="date"` 會喚起原生選擇器,體驗最佳。

雖然自訂使用者控制項是學習 ASP.NET 事件模型、ClientID、ScriptManager 的優良練習,但實務專案**強烈建議改用原生 `` 或成熟前端套件**,獲得更好相容性、無障礙支援與維護性。

copyright © 萬盛學電腦網 all rights reserved