asp.net 应用程序中的日期时间验证

本文关键字:日期 时间 验证 net 应用程序 asp | 更新日期: 2023-09-27 18:35:36

所以我有这个使用 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; 

然而,这似乎也不起作用。

如果你有耐心读到最后。你碰巧知道解决这种困境的好方法吗?

asp.net 应用程序中的日期时间验证

此行为的问题在于/符号在自定义日期时间格式中用作分隔符。

因此,然后您查看计算机上的日期时间,.NET 框架将dd/MM/yyyy替换为 dd-MM-yyyy 。因此,您可以尝试覆盖日期时间分隔符符号,就像您尝试使用 ShortDatePattern 一样,或者您可以转义格式字符串中的/符号,如下所示:dd'/'MM'/'yyyy,但我现在无法尝试。


更新:

来自 MSDN

若要更改特定日期和时间字符串的日期分隔符,请在文本字符串分隔符中指定分隔符。例如,自定义格式字符串mm'/'dd'/'yyyy生成一个结果字符串,其中/始终用作日期分隔符。

若要更改区域

性的所有日期的日期分隔符,请更改当前区域性的 DateTimeFormatInfo.DateSeparator 属性的值,或实例化 DateTimeFormatInfo 对象,将该字符分配给其 DateSeparator 属性,然后调用包含 IFormatProvider 参数的格式设置方法的重载。

所以你应该试试这个:

Thread.CurrentThread.CurrentCulture.DateTimeFormatInfo.DateSeparator = '/';
Thread.CurrentThread.CurrentUICulture.DateTimeFormatInfo.DateSeparator = '/';

@Givan是对的:

验证可能发生在服务器上。因此,将使用服务器上指定的日期格式。这也许就是为什么总是使用 MM/dd/yyyy 的原因。

您可以根据DisplayFormatAttribute中的DataFormatString指定自定义模型绑定器

public class DateFormatBinding : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        string displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, string.Format("{0} is an invalid date format", value.AttemptedValue));
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

将其添加到项目,然后在Global.asax中注册

protected void Application_Start()
{
   ...
   ModelBinders.Binders.Add(typeof(DateTime), new DateFormatBinding());
   ModelBinders.Binders.Add(typeof(DateTime?), new DateFormatBinding());
   ...
}

我想你运行的是IIS。如果是这样,请查看以下内容: IIS VS 2008/Web.config - 错误的日期格式

也许这也是有帮助的。如何在 IIS 7 中设置日期和时间格式