【问题标题】:Need to allow user to only select dates in a certain range in my view在我看来,需要允许用户只选择一定范围内的日期
【发布时间】:2014-12-12 19:08:56
【问题描述】:

我有一个 DateTime,我们使用 HTML5 来显示日期选择器,在某些情况下,只能允许用户选择特定范围内的日期。

此范围是动态的,并且基于另一个属性。

在我的模型中,我有这个属性,即日期选择器中首次显示的日期:

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

我需要此属性的 DateTime.MinValue 是同一对象中的另一个属性:

DateTime TruckPriorityDropOffFromMin { get; set; }

没有为日期时间设置范围,所以我知道我必须为此创建一个自定义方法,以便它检查 TruckPriorityDropOffFromMin 的值并将其分配给最小值。

我只是不知道该怎么做,或者是否有更好的方法可以在不使用 jquery datepicker 的情况下做到这一点。我们只需要用户只能选择TruckPriorityDropOffFromMin 属性值之后的日期。

【问题讨论】:

  • 您最好让用户从日期选择器中选择任何日期,并在提交按钮上验证他是否在您的范围内选择了它,然后显示适当的警报消息!
  • 您是否在日期输入中设置minmax 属性?

标签: c# asp.net-mvc datetime datepicker data-annotations


【解决方案1】:

如果您想在服务器端进行验证,那么您可以创建一个自定义属性类,然后使用它来验证您的对象 -

public class ValidateMinDateAttribute : ValidationAttribute
{
  private String Property { get; set; }

  public ValidateMinDateAttribute(String property)
  {
    Property = property;
  }

  protected override ValidationResult IsValid(object value, ValidationContext context)
  {
    Object instance = context.ObjectInstance;
    Type type = instance.GetType();
    Object propertyValue = type.GetProperty(Property).GetValue(instance, null);
    if (propertyValue < value or something else)//perform your check based on the value of the property, do conversion if you need
    {
      ValidationResult result = base.IsValid(value, context);
      return result;
    }
    return ValidationResult.Success;
  }
}

那就这样用吧——

[ValidateMinDate("TruckPriorityDropOffFromMin")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

但是如果你想在客户端测试它,那么你需要javascripts 来测试,比如jQuery,或者其他js 库。

注意:我现在没有视觉工作室,所以不能给出完整的代码,但这个过程应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-13
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多