asp.net mvc HTML5 日期输入类型
Posted
技术标签:
【中文标题】asp.net mvc HTML5 日期输入类型【英文标题】:asp.net mvc HTML5 date input type 【发布时间】:2015-11-17 01:23:26 【问题描述】:我在 Visual Studio 2013 中使用 asp.net mvc,其中一个字段是日期输入,但是当单击该字段并将焦点放在该字段中时,自动 html5 日期选择器不会出现。如果我手动输入该字段,它会出现,但它不会映射到该特定字段。在数据注释中,我包含了 [DataType(DataType.Date)] 但这并没有显示 HTML5 日期选择器。我如何在 asp.net 中实现这一点,特别是该字段的代码
<div class="form-group">
@Html.LabelFor(model => model.CustomerJoinDate, htmlAttributes: new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model.CustomerJoinDate, new htmlAttributes = new @class = "form-control" )
@Html.ValidationMessageFor(model => model.CustomerJoinDate, "", new @class = "text-danger" )
</div>
</div>
【问题讨论】:
将属性 type="date" 添加到 htmlattributes 括号中怎么样? 感谢大家的建议,我所做的是将 type="date" 放在“EditorFor”行的 html 属性中,这样就成功了 如果您想使用 editorfor 而不是 textboxfor,我会在我的答案中添加示例 【参考方案1】:不记得确切的添加时间,但在旧版本的 ASP.NET MVC 中,您可以修改默认编辑器模板以添加对它的支持,或者使用TextBoxFor
,它允许您指定任何自定义属性:
@Html.TextBoxFor(model => model.CustomerJoinDate, new
@class = "form-control",
type = "date"
)
【讨论】:
【参考方案2】:MVC 5.1 现在支持像这样直接使用 html 属性。您应该能够将日期放入类型属性中。
<div class="form-group">
@Html.LabelFor(model => model.CustomerJoinDate, htmlAttributes: new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model.CustomerJoinDate, new htmlAttributes = new @class = "form-control", type = "date" )
@Html.ValidationMessageFor(model => model.CustomerJoinDate, "", new @class = "text-danger" )
</div>
【讨论】:
【参考方案3】:通过TextBoxFor
查看达林关于input type="date"
的回答
"...但是当单击该字段并在该字段中获得焦点时,自动 HTML5 日期选择器不会出现"
在基础级别,not all browsers have "native" implementation of a "datepicker",因此您可能需要实现一个插件才能跨浏览器工作(例如 bootstrap datepicker 等)
例子:
<p>
See if you get a datepicker in Firefox (as of v40.0.2):
<br />
<input type="date" name="foo" />
</p>
第...
【讨论】:
【参考方案4】:如果您希望 DateTime 模型属性使用相同的模板,而不必一遍又一遍地重复相同的 Razor 代码,请在您的 Shared/EditorTemplates
文件夹中定义一个名为 DateTime.cshtml
(或 DateTime.vbhtml
)的局部视图,其中包含内容类似于:
@model DateTime
@Html.TextBoxFor(
m => m,
"0:MM/dd/yyyy",
new @class = "form-control date", type = "date" )
然后将 Razor 绑定替换为:
@Html.EditorFor(model => model.CustomerJoinDate)
等等,对于每个应该使用这个模板的日期字段。
这使用overload of TextBoxFor,允许您为输入指定format string,这有助于“屏蔽” DateTime 值的时间部分(假设您只想输入日期)。
由于not every browser supports a native datepicker,您可以在此示例中使用date
类在必要时应用polyfill(或简单地使用type=date
作为您的选择器)。
【讨论】:
以上是关于asp.net mvc HTML5 日期输入类型的主要内容,如果未能解决你的问题,请参考以下文章
将 ASP.NET 文本框呈现为 HTML5 输入类型“数字”