[转]Using the HTML5 and jQuery UI Datepicker Popup Calendar with ASP.NET MVC - Part 4
This tutorial will teach you the basics of how to work with editor templates, display templates, and the jQuery UI datepicker popup calendar in an ASP.NET MVC Web application.
Adding a Template for Editing Dates
In this section you'll create a template for editing dates that will be applied when ASP.NET MVC displays UI for editing model properties that are marked with the Date enumeration of the DataType attibute. The template will render only the date; time will not be displayed. In the template you'll use the jQuery UI Datepicker popup calendar to provide a way to edit dates.
To begin, open the Movie.cs file and add the DataType attribute with the Date enumeration to the ReleaseDate property, as shown in the following code:
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
This code causes the ReleaseDate field to be displayed without the time in both display templates and edit templates. If your application contains a date.cshtml template in the Views\Shared\EditorTemplates folder or in the Views\Movies\EditorTemplates folder, that template will be used to render any DateTime property while editing. Otherwise the built-in ASP.NET templating system will display the property as a date.
Press CTRL+F5 to run the application. Select an edit link to verify that the input field for the release date is showing only the date.
In Solution Explorer, expand the Views folder, expand the Shared folder, and then right-click the Views\Shared\EditorTemplates folder.
Click Add, and then click View. The Add View dialog box is displayed.
In the View name box, type "Date".
Select the Create as a partial view check box. Make sure that the Use a layout or master page and Create a strongly-typed view check boxes are not selected.
Click Add. The Views\Shared\EditorTemplates\Date.cshtml template is created.
Add the following code to the Views\Shared\EditorTemplates\Date.cshtml template.
@model DateTime
Using Date Template
@Html.TextBox("", String.Format("{0:d}", Model.ToShortDateString()),
new { @class = "datefield", type = "date" })
The first line declares the model to be a DateTime type. Although you don't need to declare the model type in edit and display templates, it's a best practice so that you get compile-time checking of the model being passed to the view. (Another benefit is that you then get IntelliSense for the model in the view in Visual Studio.) If the model type is not declared, ASP.NET MVC considers it a dynamic type and there's no compile-time type checking. If you declare the model to be a DateTime type, it becomes strongly typed.
The second line is just literal HTML markup that displays "Using Date Template" before a date field. You'll use this line temporarily to verify that this date template is being used.
The next line is an Html.TextBox helper that renders an input field that's a text box. The third parameter for the helper uses an anonymous type to set the class for the text box to datefield and the type to date. (Because class is a reserved in C#, you need to use the @ character to escape the class attribute in the C# parser.)
The date type is an HTML5 input type that enables HTML5-aware browsers to render a HTML5 calendar control. Later on you'll add some JavaScript to hook up the jQuery datepicker to the Html.TextBox element using the datefield class.
Press CTRL+F5 to run the application. You can verify that the ReleaseDate property in the edit view is using the edit template because the template displays "Using Date Template" just before the ReleaseDate text input box, as shown in this image:
In your browser, view the source of the page. (For example, right-click the page and select View source.) The following example shows some of the markup for the page, illustrating the class and type attributes in the rendered HTML.
<input class="datefield" data-val="true" data-val-required="Date is required"
id="ReleaseDate" name="ReleaseDate" type="date" value="1/11/1989" />
Return to the Views\Shared\EditorTemplates\Date.cshtml template and remove the "Using Date Template" markup. Now the completed template looks like this:
@model DateTime
@Html.TextBox("", String.Format("{0:d}", Model.ToShortDateString()),
new { @class = "datefield", type = "date" })
Adding a jQuery UI Datepicker Popup Calendar using NuGet
In this section you'll add the jQuery UI datepicker popup calendar to the date-edit template. The jQuery UI library provides support for animation, advanced effects, and customizable widgets. It's built on top of the jQuery JavaScript library. The datepicker popup calendar makes it easy and natural to enter dates using a calendar instead of entering a string. The popup calendar also limits users to legal dates — ordinary text entry for a date would let you enter something like 2/33/1999 ( February 33rd, 1999), but the jQuery UI datepicker popup calendar won't allow that.
First, you have to install the jQuery UI libraries. To do that, you'll use NuGet, which is a package manager that's included in SP1 versions of Visual Studio 2010 and Visual Web Developer.
In Visual Web Developer, from the Tools menu, select Library Package Manager and then select Manage NuGet Packages.

Note: If the Tools menu doesn't display the Library Package Manager command, you need to install NuGet by following the instructions on the Installing NuGet page of the NuGet website.
If you're using Visual Studio instead of Visual Web Developer, from the Tools menu, select Library Package Manager and then select Add Library Package Reference.

In the MVCMovie - Manage NuGet Packages dialog box, click the Online tab on the left and then enter "jQuery.UI" in the search box. Select jQuery UI WIdgets:Datepicker, then select the Install button.


NuGet adds these debug versions and minified versions of jQuery UI Core and the jQuery UI date picker to your project:
- jquery.ui.core.js
- jquery.ui.core.min.js
- jquery.ui.datepicker.js
- jquery.ui.datepicker.min.js
Note: The debug versions (the files without the .min.js extension) are useful for debugging, but in a production site, you'd include only the minified versions.
To actually use the jQuery date picker, you need to create a jQuery script that will hook up the calendar widget to the edit template. In Solution Explorer, right-click the Scripts folder and select Add, then New Item, and then JScript File. Name the file DatePickerReady.js.
Add the following code to the DatePickerReady.js file:
$(function () {
$(".datefield").datepicker();
});
If you're not familiar with jQuery, here's a brief explanation of what this does: the first line is the "jQuery ready" function, which is called when all the DOM elements in a page have loaded. The second line selects all DOM elements that have the class name datefield, then invokes the datepicker function for each of them. (Remember that you added the datefield class to the Views\Shared\EditorTemplates\Date.cshtml template earlier in the tutorial.)
Next, open the Views\Shared\_Layout.cshtml file. You need to add references to the following files, which are all required so that you can use the date picker:
- Content/themes/base/jquery.ui.core.css
- Content/themes/base/jquery.ui.datepicker.css
- Content/themes/base/jquery.ui.theme.css
- jquery.ui.core.min.js
- jquery.ui.datepicker.min.js
- DatePickerReady.js
The following example shows the actual code that you should add at the bottom of the head element in the Views\Shared\_Layout.cshtml file.
<link href="@Url.Content("~/Content/themes/base/jquery.ui.core.css")"
rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/themes/base/jquery.ui.datepicker.css")"
rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/themes/base/jquery.ui.theme.css")"
rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.ui.datepicker.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/DatePickerReady.js")"
type="text/javascript"></script>
The complete head section is shown here:
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")"
rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")"
type="text/javascript"></script> <link href="@Url.Content("~/Content/themes/base/jquery.ui.core.css")"
rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/themes/base/jquery.ui.datepicker.css")"
rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/themes/base/jquery.ui.theme.css")"
rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.ui.datepicker.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/DatePickerReady.js")"
type="text/javascript"></script>
</head>
The URL content helper method converts the resource path to an absolute path. You must use @URL.Content to correctly reference these resources when the application is running on IIS.
Press CTRL+F5 to run the application. Select an edit link, then put the insertion point into the ReleaseDate field. The jQuery UI popup calendar is displayed.

Like most jQuery controls, the datepicker lets you customize it extensively. For information, see Visual Customization: Designing a jQuery UI theme on the jQuery UIsite.
Supporting the HTML5 Date Input Control
As more browsers support HTML5, you'll want to use the native HTML5 input , such as the date input element, and not use the jQuery UI calendar. You can add logic to your application to automatically use HTML5 controls if the browser supports them. To do this, replace the contents of the DatePickerReady.js file with the following:
if (!Modernizr.inputtypes.date) {
$(function () {
$(".datefield").datepicker();
});
}
The first line of this script uses Modernizr to verify that HTML5 date input is supported. If it's not supported, the jQuery UI date picker is hooked up instead. (Modernizr is an open-source JavaScript library that detects the availability of native implementations of HTML5 and CSS3 . Modernizr is included in any new ASP.NET MVC projects that you create.)
After you've made this change, you can test it by using a browser that supports HTML5, such as Opera 11. Run the application using an HTML5-compatible browser and edit a movie entry. The HTML5 date control is used instead of the jQuery UI popup calendar:

Because new versions of browsers are implementing HTML5 incrementally, a good approach for now is to add code to your website that accommodates a wide variety of HTML5 support. For example, a more robust DatePickerReady.js script is shown below that lets your site support browsers that only partially support the HTML5 date control.
if (!Modernizr.inputtypes.date) {
$(function () {
$("input[type='date']")
.datepicker()
.get(0)
.setAttribute("type", "text");
})
}
This script selects HTML5 input elements of type date that don't fully support the HTML5 date control. For those elements, it hooks up the jQuery UI popup calendar and then changes the type attribute from date to text. By changing the type attribute from date to text, partial HTML5 date support is eliminated. An even more robust DatePickerReady.js script can be found at JSFIDDLE.
Adding Nullable Dates to the Templates
If you use one of the existing date templates and pass a null date, you'll get a run-time error. To make the date templates more robust, you'll change them to handle null values. To support nullable dates, change the code in the Views\Shared\DisplayTemplates\DateTime.cshtml to the following:
@model Nullable<DateTime>
@(Model != null ? string.Format("{0:d}", Model) : string.Empty)
The code returns an empty string when the model is null.
Change the code in the Views\Shared\EditorTemplates\Date.cshtml file to the following:
@model Nullable<DateTime>
@{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime) Model;
}
@Html.TextBox("", String.Format("{0:d}", dt.ToShortDateString()), new { @class = "datefield", type = "date" })
}
When this code runs, if the model is not null, the model's DateTime value is used. If the model is null, the current date is used instead.
Wrapup
This tutorial has covered the basics of ASP.NET templated helpers and shows you how to use the jQuery UI datepicker popup calendar in an ASP.NET MVC application. For more information, try these resources:
- For information on localization, see Rajeesh's blog JQueryUI Datepicker in ASP.Net MVC.
- For information about jQuery UI, see jQuery UI.
- For information about how to localize the datepicker control, see UI/Datepicker/Localization.
- For more information about the ASP.NET MVC templates, see Brad Wilson's blog series on ASP.NET MVC 2 Templates. Although the series was written for ASP.NET MVC 2, the material still applies for the current version of ASP.NET MVC.
This article was originally created on August 29, 2011
Author Information
Rick Anderson – Rick Anderson works as a programmer writer for Microsoft, focusing on ASP.NET MVC, Windows Azure and Entity Framework. You can follow him on twitter via @RickAndMSFT.
[转]Using the HTML5 and jQuery UI Datepicker Popup Calendar with ASP.NET MVC - Part 4的更多相关文章
- jQuery UI Datepicker使用介绍
本博客使用Markdown编辑器编写 在企业级web开发过程中,日历控件和图表控件是使用最多的2中第三方组件.jQuery UI带的Datepicker,日历控件能满足大多数场景开发需要.本文就主要讨 ...
- jQuery UI Datepicker&Datetimepicker添加 时-分-秒 并且,判断
jQuery UI Datepicker时间(年-月-日) 相关代码: <input type="text" value="" name="ad ...
- JQuery UI datepicker 使用方法(转)
官方地址:http://docs.jquery.com/UI/Datepicker,官方示例: http://jqueryui.com/demos/datepicker/. 一个不错的地址,用来DIY ...
- 页面日期选择控件--jquery ui datepicker 插件
日期选择插件Datepicker是一个配置灵活的插件,我们可以自定义其展示方式,包括日期格式.语言.限制选择日期范围.添加相关按钮以及其它导航等.官方地址:http://docs.jquery.com ...
- 坑爹的jquery ui datepicker
1.坑爹的jquery ui datepicker 竟然不支持选取时分秒,害的我Format半天 期间尝试了bootstrap的ditepicker,但是不起作用,发现被jquery ui 覆盖了, ...
- jQuery UI datepicker z-index默认为1 怎么处理
最近在维护一个后台系统的时候遇到这样的一个坑:后台系统中日期控件使用的是jQuery UI datepicker. 这个控件生成的日期选择框的z-index = 1.问题来了.页面上有不少z-inde ...
- Jquery UI - DatePicker 在Dialog中无法自动隐藏的解决思路
通过Jquery UI Dialog模态展示如下的一个员工编辑页面,但是遇到一个奇怪的问题:点击Start Date的input元素后,其无法失去焦点.从而导致DatePicker控件在选择日期后无法 ...
- jQuery UI Datepicker
http://www.runoob.com/try/try.php?filename=jqueryui-example-datepicker-dropdown-month-year <!doct ...
- jquery ui datepicker中文显示
$.datepicker.regional['zh-CN'] = { closeText: '关闭', prevText: '<上月', nextText: '下月>', currentT ...
随机推荐
- Mysql--连接查询
内连接查询 意义:找到表和表之间的关系或者是桥梁.连接查询是查询两个或者两个以上的表时使用的. JOIN|CROSS JOIN| INNER JOIN 通过ON 连接条件(这三个方式都行)一般 ...
- 手把手教Android商业项目-即时通讯-i美聊
[课程概况] 手把手教你从无到有的完整实现一个Android商业项目,是目前整个市场上所没有的课程,废话不多说,请往下看. [项目概况] 项目名称:i美聊 所属领域:移动社交 即时通讯 代码行数: ...
- 获取安装的apk应用信息
//获取安装的应用名称 private List<String> getInstalledAppNames(){ List<PackageInfo> packages =thi ...
- C++11新标准:decltype关键字
一.decltype意义 有时我们希望从表达式的类型推断出要定义的变量类型,但是不想用该表达式的值初始化变量(如果要初始化就用auto了).为了满足这一需求,C++11新标准引入了decltype类型 ...
- sql 语言练习题
1. 查询Student表中的所有记录的Sname.Ssex和Class列. 2. 查询教师所有的单位即不重复的Depart列. 3. 查询Student表的所有记录 . 4. 查询Score表中成绩 ...
- C#:最简洁强大的代码生成器
这是我们项目中最常用,也是最强大的代码生成器,可以自动生成 存储过程,Model,DAL,BLL 多层的脚本. 第一步:配置config,设置连接的数据库 <?xml version=" ...
- Gazebo学习随记3 图形界面的使用
直接写模型的SDF文件实在是太反人类啦! 可以在gazebo图形界面中设置好模型的链接(碰撞外观惯性),关节等等参数-然后生成SDF文件
- 乱序优化与GCC的bug
以下内容来自搜狗实验室技术交流文档,搜狐公司研发中心版权所有,仅供技术交流 摘要 --------- 乱序优化是现代编译器非常重要的特性,本文介绍了什么是乱序优化,以及由此引发的一个bug,希 ...
- 文件上传之form表单篇
form表单上传文件 作为本系列的最后一篇,也是楼主知道的第三种文件上传的方式--隆重推出Form表单 这是最传统的上传文件,提交数据的方式 Html: <form action="/ ...
- 图像标注工具labelImg安装记录
这里仅记载下labelImg的安装过程,因为有坑. 我的安装方式是从源码编译,环境ubuntu16.04,一开始是使用python2安装,从github上下载好源码,然后执行安装命令 sudo apt ...