Integrating JQuery UI Datepicker with model binding and web forms
This tutorial series demonstrates basic aspects of using model binding with an ASP.NET Web Forms project. Model binding makes data interaction more straight-forward than dealing with data source objects (such as ObjectDataSource or SqlDataSource). This series starts with introductory material and moves to more advanced concepts in later tutorials.
This tutorial shows how to add the JQuery UI Datepicker widget to a Web Form, and use model binding to update the database with the selected value.
This tutorial builds on the project created in the first and second parts of the series.
You can download the complete project in C# or VB. The downloadable code works with either Visual Studio 2012 or Visual Studio 2013. It uses the Visual Studio 2012 template, which is slightly different than the Visual Studio 2013 template shown in this tutorial.
What you’ll build
In this tutorial, you’ll:
- Add a property to your model to record the student’s enrollment date
- Enable the user to select the enrollment date using the JQuery UI Datepicker widget
- Enforce validation rules for the enrollment date
The JQuery UI Datepicker widget enables users to easily select a date from a calendar that pops up when the user interacts with the field. Using this widget can be more convenient for users than manually typing a date. Integrating the Datepicker widget into a page that uses model binding for data operations requires only a small amount of additional work.
Add a new property to the model
First, you will add a Datetime property to your Student model and migrate that change to the database. Open UniversityModels.cs, and add the highlighted code to the Student model.
[!code-csharpMain]
1: public class Student
2: {
3: [Key, Display(Name = "ID")]
4: [ScaffoldColumn(false)]
5: public int StudentID { get; set; }
6:
7: [Required, StringLength(40), Display(Name="Last Name")]
8: public string LastName { get; set; }
9:
10: [Required, StringLength(20), Display(Name = "First Name")]
11: public string FirstName { get; set; }
12:
13: [EnumDataType(typeof(YearEnum)), Display(Name = "Academic Year")]
14: public YearEnum AcademicYear { get; set; }
15:
16: [Range(typeof(DateTime), "1/1/2013", "1/1/3000", ErrorMessage="Please provide an enrollment date after 1/1/2013")]
17: [DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:d}")]
18: public DateTime EnrollmentDate { get; set; }
19:
20: public virtual ICollection Enrollments { get; set; }
21: }
The RangeAttribute is included to enforce validation rules for the property. For this tutorial, we will assume that Contoso University was founded on January 1st, 2013 and therefore earlier enrollment dates are not valid.
In the Package Management window, add a migration by running the command add-migration AddEnrollmentDate. Notice that the migration code adds the new Datetime column to the Student table. To match the value you specified in the RangeAttribute, add a default value for the new column, as shown in the highlighted code below.
[!code-csharpMain]
1: namespace ContosoUniversity.Migrations
2: {
3: using System;
4: using System.Data.Entity.Migrations;
5:
6: public partial class AddEnrollmentDate : DbMigration
7: {
8: public override void Up()
9: {
10: AddColumn("dbo.Students", "EnrollmentDate", c =>
11: c.DateTime(nullable: false, defaultValue: new DateTime(2013, 1, 1)));
12: }
13:
14: public override void Down()
15: {
16: DropColumn("dbo.Students", "EnrollmentDate");
17: }
18: }
19: }
Save your change to the migration file.
You do not need to seed the data again. Therefore, open Configuration.cs in the Migrations folder and remove or comment out the code in the Seed method. Save and close the file.
Now, run the command update-database. Notice that the column now exists in the database and all of the existing records have the default value for EnrollmentDate.
Add dynamic controls for enrollment date
You will now add controls for displaying and editing the enrollment date. At this point, the value is edited through a text box. Later in the tutorial, you will change the text box to the JQuery Datepicker widget.
First, it is important to note that you do not need to make any change to the AddStudent.aspx file. The DynamicEntity control will automatically render the new property.
Open Students.aspx, and add the following highlighted code.
[!code-aspxMain]
1: <asp:GridView runat="server" ID="studentsGrid"
2: ItemType="ContosoUniversity.Models.Student" DataKeyNames="StudentID"
3: SelectMethod="studentsGrid_GetData"
4: UpdateMethod="studentsGrid_UpdateItem" DeleteMethod="studentsGrid_DeleteItem"
5: AllowSorting="true" AllowPaging="true" PageSize="4"
6: AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
7: AutoGenerateColumns="false">
8: <Columns>
9: <asp:DynamicField DataField="StudentID" />
10: <asp:DynamicField DataField="LastName" />
11: <asp:DynamicField DataField="FirstName" />
12: <asp:DynamicField DataField="Year" />
13: <asp:DynamicField DataField="EnrollmentDate" />
14: <asp:TemplateField HeaderText="Total Credits">
15: <ItemTemplate>
16: <asp:Label Text="<%# Item.Enrollments.Sum(en => en.Course.Credits) %>"
17: runat="server" />
18: </ItemTemplate>
19: </asp:TemplateField>
20: </Columns>
21: </asp:GridView>
Run the application and notice that you can set the value of the enrollment date by typing a date. When adding a new student:
Or, editing an existing value:
Typing the date works, but it might not be the customer experience you wish to provide. In the next section, you will enable selecting a date through a calendar.
Install NuGet package to work with JQuery UI
The Juice UI NuGet package enables easy integration of the JQuery UI widgets into your web application. To use this package, install it through NuGet.
The version of Juice UI that you install may conflict with the version of JQuery in your application. Before proceeding with this tutorial, try running your application. If you encounter a JavaScript error, you need to reconcile the JQuery version. You can either add the expected version of JQuery to your Scripts folder (version 1.8.2 at time of writing this tutorial), or in Site.master specify the path to the JQuery file.
[!code-aspxMain]
1: <asp:ScriptReference Name="jquery" Path="~/Scripts/jquery-1.10.2.js" />
2: <asp:ScriptReference Path="~/Scripts/jquery-ui-1.9.2.js" />
Customize DateTime template to include Datepicker widget
You will add the Datepicker widget to the dynamic data template for editing a datetime value. By adding the widget to the template, it is automatically rendered in both the form for adding a new student and in the grid view for editing students. Open DateTime_Edit.ascx, and add the following highlighted code.
[!code-aspxMain]
1: <%@ Control Language="C#" CodeBehind="DateTime_Edit.ascx.cs" Inherits="ContosoUniversityModelBinding.DateTime_EditField" %>
2:
3: <juice:Datepicker runat="server" ID="t1" TargetControlID="TextBox1"/>
4: <asp:TextBox ID="TextBox1" runat="server" CssClass="DDTextBox" Text='<%# FieldValueEditString %>' Columns="20"></asp:TextBox>
5:
6: <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" Enabled="false" />
7: <asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator1" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" Enabled="false" />
8: <asp:DynamicValidator runat="server" ID="DynamicValidator1" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" />
9: <asp:CustomValidator runat="server" ID="DateValidator" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" EnableClientScript="false" Enabled="false" OnServerValidate="DateValidator_ServerValidate" />
In the code-behind file, you will set the minimum and maximum dates for the DatePicker. By setting these values, you will prevent users from navigating to invalid dates. You will retrieve the minimum and maximum values from the RangeAttribute on the DateTime property, if one is provided. Open DateTime_Edit.ascx.cs, and add the following highlighted code to the Page_Load method.
[!code-csharpMain]
1: protected void Page_Load(object sender, EventArgs e) {
2: TextBox1.ToolTip = Column.Description;
3:
4: SetUpValidator(RequiredFieldValidator1);
5: SetUpValidator(RegularExpressionValidator1);
6: SetUpValidator(DynamicValidator1);
7: SetUpCustomValidator(DateValidator);
8:
9: RangeAttribute ra = (RangeAttribute)Column.Attributes[typeof(RangeAttribute)];
10: if (ra != null)
11: {
12: t1.MinDate = ra.Minimum.ToString();
13: t1.MaxDate = ra.Maximum.ToString();
14: }
15: }
Run the web application and navigate to the AddStudent page. Provide values for the fields and notice that when you click on the text box for Enrollment Date, the calendar is displayed.
Pick a date, and click Insert. The RangeAttribute enforces validation on the server. By setting the minDate property on the Datepicker, you also apply validation on the client. The calendar does not let the user navigate to a date prior to the value of minDate.
When you edit a record in the grid view, the calendar is also displayed.
Conclusion
In this tutorial, you learned how to incorporate a JQuery widget into a web form that uses model binding.
In the next tutorial, you will use a query string value when selecting data.
|