【问题标题】:Default Range Validation on ASP MVC Model propertiesASP MVC 模型属性的默认范围验证
【发布时间】:2021-01-29 19:25:38
【问题描述】:

有没有办法让 ASP MVC 5 将所有类型视为应用了范围最小值和最大值?

也就是说,这样就不必将范围属性添加到每个可能的属性中?

[Range(0, int.MaxValue, ErrorMessage = "Value beyond accepted range")]
public int? Thing{ get; set; }

[Range(0, int.MaxValue, ErrorMessage = "Value beyond accepted range")]
public int? AnotherThing { get; set; }

并且在属性具有指定范围属性的地方使用该属性(覆盖默认行为)?

为每个属性添加范围验证器非常重复和乏味,并且会破坏 DRY。

我认为它可能在每个属性类型的编辑器模板中完成?

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    设法解决了:

    编辑器模板:Int.cshtml

    @model int?
    
    @{
       
        var htmlAttributes = new RouteValueDictionary();
    
        var range = ViewData.ModelMetadata.GetPropertyAttribute<RangeAttribute>();
    
        if (range == null)
        {
            htmlAttributes.Add("data-val-range_min", "0");
            htmlAttributes.Add("data-val-range_max", int.MaxValue);
            htmlAttributes.Add("data-val-range", "value exceeds allowed range");
        }
    
        htmlAttributes.Add("class", "form-control");
        htmlAttributes.Add("type", "number");
    
    }
    
    @Html.TextBoxFor(model => model, htmlAttributes)
    

    模型元数据扩展:

    public static T GetPropertyAttribute<T>(this ModelMetadata instance)
      where T : Attribute
    {
        var result = instance.ContainerType
          .GetProperty(instance.PropertyName)
          .GetCustomAttributes(typeof(T), false)
          .Select(a => a as T)
          .FirstOrDefault(a => a != null);
    
        return result;
    }
    

    【讨论】:

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