0
我想從xml配置中附加自定義屬性,請幫我解決這個問題。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 };
}
}
我已創建模型,然後屬性類的自定義屬性類,但現在我想添加的這些註釋即顯示,RequiredIf從XML配置(自定義屬性)的數據。