0

标题看起来有点奇怪对不起。

好吧,我是 Asp.net MVC 3 的新手。我想为我的一个属性创建一个属性,该属性的名称是国家身份证号码。

    public class IdentityNumberControl : ActionFilterAttribute
{
    public string WrongIdentityNumber { get; set; }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        if(??? )
        {
            filterContext.HttpContext.Response.Write(WrongIdentityNumber);
            return;
        }
        base.OnActionExecuting(filterContext);
    }
}

我的会员班在这里

 public class Member
{
    public int ID { get; set; }
    [Required(ErrorMessage = "You have to enter your name")]
    [StringLength(50, ErrorMessage  ="Your name length can not be less than{2} more than {1} ", MinimumLength = 3)]
    [Display("Name :")]
    public string Name { get; set; }

    [Required(ErrorMessage = "You have to enter your surname")]
    [StringLength(40, ErrorMessage = "Your surname length can not be less than{2} more than {1} ", MinimumLength = 2)]
    [Display("Surname :")]
    public string SurName { get; set; }

    [Required(ErrorMessage = "You have to enter your password")]
    [StringLength(20, ErrorMessage = "Your name lengt can not be less than{2} more than {1} ", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display("Password :")]
    public string Password { get; set; }
    public string PasswordSalt { get; set; }

    [IdentityNumberControl(WrongIdentityNumber = "It is not a valid identity number")]
    public double IdentityNumber { get; set; }

}

所以我想检查identitynumber是否正确(我有一个计算方法来确认它)我知道我必须在IdentityNumberControl类中编写代码。但我不知道如何在 OnActionExecuting 方法中获取 identitynumber 的值。

我希望我能解释我的问题

4

1 回答 1

0

这是我的解决方案

public class IdentityNumberAttribute : ValidationAttribute
{
    private string WrongIdentityNumber;

    public IdentityNumberAttribute(string message)
    {
        WrongIdentityNumber = message;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {

        string identityNumber = value.ToString();

        if (identityNumber.Length != 11)
            return new ValidationResult(WrongIdentityNumber);

        int sum = 0;


        for (int i = 0; i < identityNumber.Length - 1; i++)
        {
            sum += Convert.ToInt32(identityNumber[i].ToString());
        }

        return sum.ToString()[1] == identityNumber[10]
                   ? ValidationResult.Success
                   : new ValidationResult(WrongIdentityNumber);
    }
}

它计算出是否有效的土耳其国民身份证号码

你可以这样使用这个属性

    [IdentityNumber("It is not a valid identity number")]
    [Required(ErrorMessage = "You have to enter your identity number")]
    [DisplayName("National Identity Number:")]
    public string IdentityNumber { get; set; }
于 2012-12-18T10:46:05.700 回答