由 Tom FitzMacken 撰寫
本教學系列示範在 ASP.NET Web Forms 專案中使用模型綁定的基本面向。 模型綁定使資料互動比處理資料來源物件(如 ObjectDataSource 或 SqlDataSource)更為直接。 這個系列從入門教材開始,後續教學會進入更進階的概念。
這個教學示範如何將 JQuery UI Datepicker 小工具 加入 Web 表單,並利用模型綁定更新資料庫並取得所選值。
你可以 下載 使用 C# 或 VB 的完整專案。 可下載的程式碼可搭配 Visual Studio 2012 或 Visual Studio 2013 使用。 它使用 Visual Studio 2012 模板,與本教學中展示的 Visual Studio 2013 模板略有不同。
你將會建構什麼
在本教學課程中,您將會:
- 在模型中新增一個物件以記錄學生的註冊日期
- 啟用使用者使用 JQuery UI Datepicker 小工具選擇註冊日期
- 強制執行報名日期的驗證規則
JQuery UI Datepicker 小工具讓使用者能輕鬆從使用者互動欄位時跳出的日曆中選擇日期。 使用這個小工具對使用者來說比手動輸入日期更方便。 將 Datepicker 元件整合到使用模型綁定進行資料操作的頁面中,只需少量額外工作。
新增一個屬性到模型中
首先,你會在學生模型中新增 一個 Datetime 屬性,並將該變更遷移到資料庫中。 打開 UniversityModels.cs,並將高亮的程式碼加入學生模式。
public class Student
{
[Key, Display(Name = "ID")]
[ScaffoldColumn(false)]
public int StudentID { get; set; }
[Required, StringLength(40), Display(Name="Last Name")]
public string LastName { get; set; }
[Required, StringLength(20), Display(Name = "First Name")]
public string FirstName { get; set; }
[EnumDataType(typeof(YearEnum)), Display(Name = "Academic Year")]
public YearEnum AcademicYear { get; set; }
[Range(typeof(DateTime), "1/1/2013", "1/1/3000", ErrorMessage="Please provide an enrollment date after 1/1/2013")]
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:d}")]
public DateTime EnrollmentDate { get; set; }
public virtual ICollection Enrollments { get; set; }
}
RangeAttribute 是用來強制執行該屬性的驗證規則。 在本教學中,我們將假設 Contoso 大學成立於 2013 年 1 月 1 日,因此較早的入學日期不適用。
在套件管理視窗中,執行 add-migration AddEnrollmentDate 指令來新增遷移。 請注意,遷移程式碼會將新的 Datetime 欄位加入 Student 資料表。 為了符合你在 RangeAttribute 中指定的值,請為新欄位加入預設值,如下方標示的程式碼所示。
namespace ContosoUniversity.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddEnrollmentDate : DbMigration
{
public override void Up()
{
AddColumn("dbo.Students", "EnrollmentDate", c =>
c.DateTime(nullable: false, defaultValue: new DateTime(2013, 1, 1)));
}
public override void Down()
{
DropColumn("dbo.Students", "EnrollmentDate");
}
}
}
把你的變更存到遷移檔案裡。
你不需要再次初始化數據。 因此,請在 Migrations 資料夾中開啟 Configuration.cs ,並以 Seed 方法移除或註解程式碼。 儲存並關閉檔案。
現在,執行 update-database 指令。 請注意,該欄位現在已在資料庫中存在,且所有現有紀錄的預設值都是 EnrollmentDate。
新增註冊日期的動態控制
你現在將新增顯示與編輯註冊日期的控制項。 此時,數值會透過文字框進行編輯。 在教學後面,你會把文字框改成 JQuery Datepicker 小工具。
首先,重要的是要注意,你不需要對 AddStudent.aspx 檔案做任何更改。 DynamicEntity 控制項會自動渲染這個新屬性。
打開 Students.aspx,並加入以下標示的程式碼。
<asp:GridView runat="server" ID="studentsGrid"
ItemType="ContosoUniversity.Models.Student" DataKeyNames="StudentID"
SelectMethod="studentsGrid_GetData"
UpdateMethod="studentsGrid_UpdateItem" DeleteMethod="studentsGrid_DeleteItem"
AllowSorting="true" AllowPaging="true" PageSize="4"
AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
AutoGenerateColumns="false">
<Columns>
<asp:DynamicField DataField="StudentID" />
<asp:DynamicField DataField="LastName" />
<asp:DynamicField DataField="FirstName" />
<asp:DynamicField DataField="Year" />
<asp:DynamicField DataField="EnrollmentDate" />
<asp:TemplateField HeaderText="Total Credits">
<ItemTemplate>
<asp:Label Text="<%# Item.Enrollments.Sum(en => en.Course.Credits) %>"
runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
執行應用程式後,發現你可以輸入日期來設定登記日期的值。 新增學生時:
或者,編輯現有的數值:
輸入日期是可行的,但可能不是你想要的客戶體驗。 在下一節,你將啟用透過行事曆選擇日期。
安裝 NuGet 套件以配合 JQuery UI 運作
Juice UI NuGet 套件讓 JQuery UI 小工具能輕鬆整合到你的網頁應用程式中。 使用此套件時,請透過 NuGet 安裝。
你安裝的 Juice UI 版本可能會和你應用程式中的 JQuery 版本衝突。 在繼續這個教學之前,先試著執行你的應用程式。 如果你遇到 JavaScript 錯誤,你需要對 JQuery 版本進行對照。 你可以將預期版本的 JQuery 加入你的 Scripts 資料夾(撰寫本教學時版本為 1.8.2),或在 Site.master 指定 JQuery 檔案的路徑。
<asp:ScriptReference Name="jquery" Path="~/Scripts/jquery-1.10.2.js" />
<asp:ScriptReference Path="~/Scripts/jquery-ui-1.9.2.js" />
自訂 DateTime 範本以包含 Datepicker 小工具
你會將 Datepicker 小工具加入動態資料範本,以便編輯 Datetime 值。 將 widget 加入範本後,它會自動在新增學生的表單和編輯學生的網格視圖中呈現。 打開 DateTime_Edit.ascx,並加入以下標示的程式碼。
<%@ Control Language="C#" CodeBehind="DateTime_Edit.ascx.cs" Inherits="ContosoUniversityModelBinding.DateTime_EditField" %>
<juice:Datepicker runat="server" ID="t1" TargetControlID="TextBox1"/>
<asp:TextBox ID="TextBox1" runat="server" CssClass="DDTextBox" Text='<%# FieldValueEditString %>' Columns="20"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" Enabled="false" />
<asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator1" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" Enabled="false" />
<asp:DynamicValidator runat="server" ID="DynamicValidator1" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" />
<asp:CustomValidator runat="server" ID="DateValidator" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" EnableClientScript="false" Enabled="false" OnServerValidate="DateValidator_ServerValidate" />
在程式碼後面檔案中,你會設定DatePicker的最小與最大日期。 透過設定這些值,你可以避免使用者瀏覽到無效的日期。 你會從 DateTime 屬性的 RangeAttribute 中取得最小值和最大值,如果有提供的話。 打開 DateTime_Edit.ascx.cs,並將以下標示的程式碼加入Page_Load方法。
protected void Page_Load(object sender, EventArgs e) {
TextBox1.ToolTip = Column.Description;
SetUpValidator(RequiredFieldValidator1);
SetUpValidator(RegularExpressionValidator1);
SetUpValidator(DynamicValidator1);
SetUpCustomValidator(DateValidator);
RangeAttribute ra = (RangeAttribute)Column.Attributes[typeof(RangeAttribute)];
if (ra != null)
{
t1.MinDate = ra.Minimum.ToString();
t1.MaxDate = ra.Maximum.ToString();
}
}
執行網頁應用程式並導向 AddStudent 頁面。 請為欄位提供數值,並注意點擊「登記日期」的文字框時,日曆會顯示出來。
選擇一個日期,然後點擊 「插入」。 RangeAttribute 會強制伺服器驗證。 在 Datepicker 上設定 minDate 屬性,同時也對用戶端套用驗證。 行事曆不允許使用者導覽到 minDate 值之前的日期。
當你在格狀視圖中編輯記錄時,日曆也會顯示出來。
結論
在這個教學中,你學會了如何將 JQuery 小工具整合到使用模型綁定的網頁表單中。
在下一個 教學中,你將使用查詢字串值來選擇資料。