Asp.net mvc 3 Asp.net MVC maxlength无法使用数据批注

Asp.net mvc 3 Asp.net MVC maxlength无法使用数据批注,asp.net-mvc-3,Asp.net Mvc 3,我使用的是asp.net mvc 4,我在模型中使用的是[maxlength(2)],但它不适用于客户端验证。我是asp.net mvc新手。这是我的代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace RestrauntsMVC.Models { public

我使用的是asp.net mvc 4,我在模型中使用的是[maxlength(2)],但它不适用于客户端验证。我是asp.net mvc新手。这是我的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace RestrauntsMVC.Models
{
  public class Restraunts
  {

    public int id { get; set; }
    [Required]
    public string name { get; set; }
    [Required]
    [MaxLength(2),MinLength(1)]
    public int rating { get; set; }
    [Required]
    public string location { get; set; }
  }
}

我找到了答案myslef,它适用于Maxlength,minlength代表字符串,而不是整数

using System;
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.ComponentModel.DataAnnotations;  
namespace RestrauntsMVC.Models
{
public class Restraunts
{

    public int id { get; set; }
    [Required]
    public string name { get; set; }
    [Required]
    [Range(1,10,ErrorMessage="Rating must between 1 to 10")]        
    public int rating { get; set; }
    [Required]
    public string location { get; set; }
}
}

像其他提到的只是字符串,那么写你自己的呢

使用System.ComponentModel.DataAnnotations;
内部类MaxDigitAttribute:ValidationAttribute
{
私人整数最大值,
闵;
公共MaxDigitAttribute(int max,int min=0)
{
Max=Max;
Min=Min;
}
受保护的重写ValidationResult有效(对象值,ValidationContext ValidationContext)
{
如果(!IsValid(值))
{
返回新的ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
返回null;
}
公共覆盖布尔值有效(对象值)
{
//你可以做任何你喜欢的自定义验证
if(值为int)
{
var stringValue=“”+(int)值;
var length=stringValue.length;

如果(长度>=Min&&length其他验证是否正常工作?是,必填字段正常工作..是否尝试了
[范围(1,2)]
。我认为MaxLength适用于字符串类型。.是的,rage验证器可以工作,但我不确定MaxLength为什么不工作。.谢谢Pabloker。.长度:它可以有多少个字符。范围:它可以有多少个值。MaxLength用于指定属性的最大长度,而不是最大数值:为什么回答您的问题自己的答案…?@WiiMaxx,因为我自己找到了答案,我想帮助其他将来也会阅读的用户。
using System.ComponentModel.DataAnnotations;

internal class MaxDigitsAttribute : ValidationAttribute
{
    private int Max,
                Min;

    public MaxDigitsAttribute(int max, int min = 0)
    {
        Max = max;
        Min = min;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (!IsValid(value))
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }

    public override bool IsValid(object value)
    {
        // you could do any custom validation you like
        if (value is int)
        {
            var stringValue = "" + (int)value;
            var length = stringValue.Length;
            if (length >= Min && length <= Max)
                return true;
        }

        return false;
    }
}