【发布时间】:2015-02-25 11:27:20
【问题描述】:
所以我使用 razor 和 C# 构建了这个 asp.net 应用程序,但我无法验证日期时间是否正常工作。
以下是我的应用的相关部分。
public class EmployeeDto
{
...
[Required]
[DataMember]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] // from what I understand this should format the date on the view ackording to the string
public Nullable<DateTime> inDate { get; set; }
...
[Required]
[DataMember]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<DateTime> birthDate { get; set; }
[DataMember]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<DateTime> createdDate { get; set; }
...
}
此 DTO 也用作视图模型。
在添加员工视图中,我们使用日期选择器来编辑前两个日期。第三个是隐藏的。
这是视图的样子
@model StratecEMS.Application.DTO.EmployeeDto
<style type="text/css">...</style>
<script type="text/javascript">
$(function () {
$("#birthDate").datepicker({ dateFormat: 'dd/mm/yy' });
$("#inDate").datepicker({ dateFormat: 'dd/mm/yy' });
});
...
</script>
...
<fieldset>
<legend>New Employee Details</legend>
@using (Html.BeginForm("AddEmployee", "Administration", FormMethod.Post, new { id = "AddEmployeeForm" }))
{
@Html.HiddenFor(model => Model.createdDate)
<div class="editor-label">
@Html.Label("In Date:")
@Html.EditorFor(model => model.inDate)
@Html.ValidationMessageFor(model => model.inDate)
</div>
<div class="editor-label">
@Html.Label("Birthdate:")
@Html.EditorFor(model => model.birthDate)
@Html.ValidationMessageFor(model => model.birthDate)
</div>
}
</fieldset>
现在这是我的问题: 在我的电脑上,我有国际格式的日期“yyyy-MM-dd”。 在应用程序中,我们需要日期始终采用自定义格式“dd/MM/yyyy”,但验证始终以美国格式“MM/dd/yyyy”完成,我不知道为什么会发生这种情况。
在将 DisplayFormat 属性添加到 DTO 后,为了让事情变得更加奇怪,我的 UI 上显示的两个日期以这种格式“dd-MM-yyyy”显示。哇!?!但验证仍以美国格式完成。
我可以通过在文本框中输入美国格式的日期来绕过对birthDate 和inDate 的验证,但是对于createdDate 没有这样的解决方法,它总是隐藏并保留在国际格式中。
我还尝试通过使用这段代码在 Global.asax Application_Start 方法中设置线程文化来更改应用程序的文化
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
但是这似乎也不起作用。
如果你有耐心读到最后。您碰巧知道解决这种困境的好方法吗?
【问题讨论】:
-
你的意思是 - 客户端验证?
-
作为一种解决方法 - 您可以尝试改用正则表达式验证
-
验证可能发生在您的服务器上。因此将使用服务器上指定的日期格式。这也许就是为什么总是使用 MM/dd/yyyy 的原因。
-
@Giwan,用于测试我的开发 PC 也是服务器。尚未部署应用程序。
标签: c# asp.net validation datetime razor