asp.net aplication中的日期时间验证

时间:2014-12-29 09:12:39

标签: c# asp.net validation datetime razor

所以我使用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>

现在我的问题出在这里: 在我的电脑上,我有国际格式的日期&#34; yyyy-MM-dd&#34;。 在应用程序中,我们需要日期始终采用自定义格式&#34; dd / MM / yyyy&#34;但是验证总是以美国格式进行,并且#34; MM / dd / yyyy&#34;而且我不知道为什么会这样。

为了在将DisplayFormat属性添加到DTO后使事情变得更加奇怪,我的UI上显示的两个日期以这种格式显示&#34; dd-MM-yyyy&#34;。 WTF!?!但验证是以美国格式完成的。

我可以通过在文本框中输入美国格式的日期来解决birthDate和inDate的验证问题,但是createDate没有这样的解决方法,它始终是隐藏的并保留为国际格式。 / p>

我还试图通过使用这段代码在Global.asax Application_Start方法中设置线程文化来改变应用程序的文化

var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture; 

然而,这似乎也无法奏效。

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

3 个答案:

答案 0 :(得分:2)

此行为的问题是/符号在Custom DateTime formatting中用作分隔符。

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


更新

来自MSDN

  
    

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

         

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

  

所以你应该试试这个:

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

@Givan是对的:

  
    

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

  

答案 1 :(得分:1)

您可以根据DataFormatString

中的DisplayFormatAttribute指定自定义模型绑定器
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());
   ...
}

答案 2 :(得分:0)

我猜你正在运行IIS。如果有,请查看:IIS VS 2008 / Web.config - wrong date format

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