来自xml的数据注释和自定义属性

时间:2013-07-04 11:48:19

标签: data-annotations custom-attributes

我想从xml配置中附加自定义属性,请帮我解决这个问题。

public partial class User
{
    public Nullable<int> UserId { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }

    public Nullable<int> salary { get; set; }
}

[MetadataType(typeof(CUserAttributes))]
public class Cuser : User
{
    public Nullable<bool> IsRequire { get; set; }
}

//[Serializable]
public class CUserAttributes
{

    [Required]
    public Nullable<bool> IsRequire { get; set; }

    [Display(Name="My UserId")]
    [RequiredIf(IsRequiredPropertyName = "IsRequire", ErrorMessage = "required.")]
    public Nullable<int> UserId { get; set; }

    [RequiredIf(IsRequiredPropertyName = "IsRequire", ErrorMessage = "required.")]
    public string UserName { get; set; }

    [RequiredIf(IsRequiredPropertyName = "IsRequire", ErrorMessage = "required.")]
    public string Password { get; set; }

    [RequiredIf(IsRequiredPropertyName = "IsRequire", ErrorMessage = "required.")]
    public Nullable<int> salary { get; set; }

}

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RequiredIf : ValidationAttribute, IClientValidatable
{
    public string IsRequiredPropertyName { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var isRequiredName = validationContext.ObjectInstance.GetType().GetProperty(this.IsRequiredPropertyName);
        var isRequiredNameValue = isRequiredName.GetValue(validationContext.ObjectInstance, null);

        if (isRequiredNameValue != null)
        {
            if (Convert.ToBoolean(isRequiredNameValue) == true)
            {
                if (value == null)
                {
                    return new ValidationResult(this.ErrorMessage);
                }
            }
        }
        else if (isRequiredNameValue == null)
        {
            throw new Exception("RequiredIf property value is not found");
        }
        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule mcvr = new ModelClientValidationRule();
        mcvr.ValidationType = "requiredif";
        mcvr.ErrorMessage = this.ErrorMessage;
        mcvr.ValidationParameters.Add("isrequiredpropertyname", this.IsRequiredPropertyName);
        return new List<ModelClientValidationRule> { mcvr };
    }

}

我创建了Model,Attributes类,然后创建了自定义属性类,但现在我想从XML配置中添加那些数据注释,即Display,RequiredIf(自定义属性)。

1 个答案:

答案 0 :(得分:0)

可以从xml获取验证配置, 你可以点击以下链接

http://www.primaryobjects.com/CMS/Article141.aspx