首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >asp.net应用中的日期时间验证

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

Stack Overflow用户
提问于 2014-12-29 09:12:39
回答 3查看 3.7K关注 0票数 2

因此,我使用剃须刀和C#构建了这个C#应用程序,并且无法获得日期时间的验证来正确工作。

以下是我的应用程序的相关部分。

代码语言:javascript
复制
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也用作视图模型。

在视图上,我们使用日期选择器来编辑前两个日期.第三个是隐藏的。

这里的风景是什么样子

代码语言:javascript
复制
 @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”。在应用程序中,我们需要日期始终是自定义格式"dd/MM/yyyy“,但是验证总是以美国格式"MM/dd/yyyy”进行,我不知道为什么会发生这种情况。

在将DisplayFormat属性添加到DTO之后,为了使事情变得更加奇怪,显示在我的UI上的两个日期以“dd”格式显示。哇!?!但验证是以美国格式进行的。

我可以通过在文本框中输入美国格式的日期来绕过birthDate和inDate的验证,但是createdDate没有这样的解决办法,因为createdDate总是隐藏的,并且保持在国际格式中。

我还试图通过使用以下代码在Global.asax Application_Start方法中设置线程区域性来更改应用程序的区域性

代码语言:javascript
复制
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture; 

然而,这似乎也是行不通的。

如果你有耐心读到最后。你知道解决这个困境的好办法吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-12-29 09:29:20

这种行为的问题是,/符号在自定义DateTime格式中用作分隔符。

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

更新:

来自MSDN

若要更改特定日期和时间字符串的日期分隔符,请在文字字符串分隔符中指定分隔符字符。例如,自定义格式字符串mm'/'dd'/'yyyy生成一个结果字符串,其中始终使用/作为日期分隔符。若要更改区域性的所有日期的日期分隔符,请更改当前区域性的DateTimeFormatInfo.DateSeparator属性的值,或实例化DateTimeFormatInfo对象,将字符分配给其DateSeparator属性,并调用包含IFormatProvider参数的格式化方法的重载。

所以你应该试试这个:

代码语言:javascript
复制
Thread.CurrentThread.CurrentCulture.DateTimeFormatInfo.DateSeparator = '/';
Thread.CurrentThread.CurrentUICulture.DateTimeFormatInfo.DateSeparator = '/';

@Givan是对的:

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

票数 2
EN

Stack Overflow用户

发布于 2014-12-29 09:56:05

您可以基于DataFormatStringDisplayFormatAttribute中指定自定义模型绑定器。

代码语言:javascript
复制
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中注册

代码语言:javascript
复制
protected void Application_Start()
{
   ...
   ModelBinders.Binders.Add(typeof(DateTime), new DateFormatBinding());
   ModelBinders.Binders.Add(typeof(DateTime?), new DateFormatBinding());
   ...
}
票数 1
EN

Stack Overflow用户

发布于 2014-12-29 13:49:03

我猜你是在跑IIS。如果是这样的话,请看以下内容:IIS 2008 / Web.config -错误的日期格式

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27686124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档