【发布时间】:2018-02-14 10:06:48
【问题描述】:
我在 MVC5 asp.net 项目中使用 dd/MMM/YYYY 格式的日期时遇到问题。主要在 Chrome 上,因为它似乎只接受格式为 yyyy/mm/dd 的日期。
为了规范跨浏览器的行为,我使用了 jquery datetimepicker 组件。
我尝试了很多方法,但 Chrome 仍然说日期无效。即使将输入定义为文本而不是日期。
此外,即使我关闭了对该特定组件的验证 (data-val="false"),Chrome 仍然坚持将日期标记为无效。
型号:
public class order
{
[Key]
public int orderID { get; set; }
[Required]
public string comments { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}", ApplyFormatInEditMode = false)]
[Display(Name = "Date of Shipping")]
public DateTime date { get; set; }
}
查看日期输入:
<div class="form-group">
@Html.LabelFor(model => model.date, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.date, new { htmlAttributes = new { @class = "form-control datetimepicker" } })
@Html.ValidationMessageFor(model => model.date, "", new { @class = "text-danger" })
</div>
</div>
进口:
<script src="https://code.jquery.com/jquery-3.2.1.js"/script>
<link rel="stylesheet" type="text/css" href="~/Content/jquery.datetimepicker.min.css" />
<script src="~/Scripts/jquery.datetimepicker.full.min.js"></script>
Javascript:
<script type="text/javascript">
jQuery.datetimepicker.setLocale('es');
jQuery('#date').datetimepicker({
format: 'd/M/Y',
});
</script>
【问题讨论】:
-
如果您使用 jquery datepicker,那么拥有
[DataType(DataType.Date)]和[DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}", ApplyFormatInEditMode = true)]毫无意义(然后您可以删除new { @type = "text" } -
如果您收到客户端错误,那是因为
jquery.validate根据MM/dd/yyyy格式验证日期。您需要重新配置验证器以接受您的格式的日期 -
删除
@type = "text"- 此属性不相关。此外,您的 datetimepicker 格式似乎是错误的 - 它应该是$('#date').datetimepicker({format : "DD/MMM/YYYY"})。然后设置客户端验证:$.validator.methods.date = function (value, element) { return this.optional(element) || $.datetimepicker.parseDate('DD/MMM/YYYY', value); } -
@StephenMuecke,有远程 DateType 注释和
new { @type = "text" },因为你说不需要。 -
@TetsuyaYamamoto,格式很好,因为我正在使用来自xdsoft.net/jqplugins/datetimepicker 的 datetimepicker,并且是正确的格式。对于验证器方法,parseDate 不存在,我应该包含一个 java 脚本库还是缺少一些东西?
标签: c# asp.net-mvc html