【问题标题】:Date Time validation in asp.net aplicationasp.net 应用程序中的日期时间验证
【发布时间】: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


【解决方案1】:

这种行为的问题在于/ 符号在Custom DateTime formatting 中用作分隔符。

因此,然后您在计算机上查看日期时间,.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 的原因。

【讨论】:

  • 这是解决方案的一部分。我设法在它的构造函数中为控制器线程设置了文化:( Global.asax 中的代码似乎没有达到预期的效果。验证现在对 UI 上显示的日期非常有效,但隐藏日期的字符串是视图仍以“yyyy-MM-dd”格式返回。并以我的自定义格式进行验证。
  • 我终于决定用隐藏的 div &lt;div class="editor-label" style="display: none" &gt; @Html.Label("Created Date:") @Html.EditorFor(model =&gt; Model.createdDate) @Html.ValidationMessageFor(model =&gt; Model.createdDate) &lt;/div&gt; 替换 @Html.HiddenFor(model =&gt; Model.createdDate),一切正常
【解决方案2】:

您可以在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());
   ...
}

【讨论】:

    【解决方案3】:

    我猜你运行的是 IIS。如果是这样,请查看:IIS VS 2008 / Web.config - wrong date format

    也许这也有帮助。 How to set Date and time format in IIS 7

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多