【问题标题】:DataAnnotation [DataType(DataType.Date)] makes my field unnecessarily RequiredDataAnnotation [DataType(DataType.Date)] 使我的字段不必要地必需
【发布时间】:2015-10-31 00:07:32
【问题描述】:

我的 ViewModel 中有以下字段:

    [DataType(DataType.Date)]
    [Display(Name = "Preferred date)")]
    public DateTime EventDate { get; set; }

产生以下标记:

<input class="input-validation-error form-control text-box single-line" data-val="true" data-val-date="The field Preferred date must be a date." data-val-required="The Preferred date field is required." id="EventDate" name="EventDate" type="date" value="">

如果用户没有选择值(即,将此字段留空 - value=""),则返回给 ViewModel 的数据是“{1/1/0001 12:00:00 AM}”,ModelState.IsValidfalse.

我不希望这个字段是必需的!

我试图用我的标记替换:

<input class="form-control text-box single-line" id="EventDate" name="EventDate" type="date" value="1/1/1980">

但是,返回的值仍然是“{1/1/0001 12:00:00 AM}”,ModelState.IsValidfalse

如何禁用此字段的必填验证(仅)?提前致谢。

【问题讨论】:

  • 将日期时间更改为日期时间? (使可空)可以解决它
  • @Murilo,很抱歉我的理解不够,请您详细说明一下吗?
  • 公开日期时间?事件日期 { 获取;放; }
  • [DataType(DataType.Date)] 不会使您的属性成为必需的-该属性所做的只是告诉@Html.EditorFor() 方法呈现type="date"。它是必需的,因为 typeof DateTime 不能有 null 值。

标签: asp.net asp.net-mvc validation data-annotations


【解决方案1】:

感谢穆里洛,我会发布答案:

我将 ViewModel 字段更改为:

public DateTime EventDate { get; set; }

public Nullable<DateTime> EventDate { get; set; }

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2012-08-31
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    相关资源
    最近更新 更多