【问题标题】:server side data annotation not working properly for DateTime array type服务器端数据注释不适用于 DateTime 数组类型
【发布时间】:2019-11-12 13:30:37
【问题描述】:

我的模型中有一个用于 DateRangePickerFor 组件的数组类型 DateTime 属性。 型号:

public class DateRange
{
    [Required(ErrorMessage = "Please enter the value")]
    public DateTime?[] value { get; set; }
}

执行 post 操作时,模型值采用以下类型。由于此控件默认需要两个数组值,并且由于可以为空类型,因此我得到了以下值。

{System.DateTime?[2]}
[0]: null
[1]: null

因此,在这种情况下,值被设置为 value[null, null] 并且没有设置给定的注释“请输入值”。 因此,任何人都可以建议处理 DateTime 数组类型并使 Data 注释适用于这种情况的方法。 控制器:

  public IActionResult Index()
  {
      return View();
  }

  [HttpPost]
  public IActionResult Index(DateRange model)
  {
      //posted value is obtained from the model
      DateRangeValue.value = model.value;
      return View(DateRangeValue);
  }

查看:

<form method="post">
    // Here i use my custom component (i.e) DateRangerPicker which takes the two date array values and displays like this "3/3/2020 - 9/3/2021"
    @Html.DateRangePickerFor(m => m.value)

    <input type="submit" value="Save Student Details" />
</form>

【问题讨论】:

    标签: c# asp.net-core data-annotations html-helper


    【解决方案1】:

    我建议修改您的自定义组件,使其采用两个单独的属性,而不是DateTime? 类型的二维数组。您的数组本身不是空的,只是它的两个元素的值,因此您没有收到错误消息。

    【讨论】:

    • 我的要求是传递数组类型DateTime?而且我无法修改我的自定义组件。实际上我的帖子只是空的,但类型为 system.DateTime[null,null]。因此我只需要处理这种情况。如果我在发布操作中将此类型更改为 null 也意味着未设置注释值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多