2013-03-21 2 views
3

데이터 주석 속성을 사용하여 텍스트를 조작하고 조작 후 새 값을 반환 할 수 있습니까?속성의 값을 대체하기위한 데이터 주석?

예를 들어 단어 사이에 특수 문자 또는 여러 공백이있는 문자열 속성의 유효성을 검사 한 다음 원래 속성의 값을 바꾸기 위해 새 문자열을 반환하고 싶습니다.

데이터 주석을 사용하는 것이 가능한가요?

+0

get/set 부분에서 수행 할 수 없습니까? 'Property {get {return _Property.Replace (badChar, goodChar)}; }}' – Corak

+0

더 나은 접근 방식은 DataBinder라고 생각합니다. http://stackoverflow.com/a/1734025/7720 – Romias

답변

1

Corak의 제안이에 하위 클래스에 검증에서 다양한 솔루션을주의하는 것이 재미있다 가장 좋은 방법. 그러나 기본 클래스를 작성할 수 있으며 리플렉션을 사용하면 멤버 유형의 내용으로 원하는 모든 작업을 수행 할 수 있습니다.

2

답할 시간이 조금 모자라지만 (2 년), 맞춤 DataAnnotations 속성에서 유효성을 검사 할 값을 수정할 수 있습니다. 열쇠는 ValidationAttribute의 IsValid(Object, ValidationContext) 메서드를 재정의하고 약간의 반사 마법 수행 : Dado.ComponentModel.Mutations

이 예는 잘못된 문자가 제거되었는지 확인합니다 : 여기

public class MyCustomValidationAttribute : ValidationAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext ctx) 
    { 
     // get the property 
     var prop = ctx.ObjectType.GetProperty(ctx.MemberName); 

     // get the current value (assuming it's a string property) 
     var oldVal = prop.GetValue(ctx.ObjectInstance) as string; 

     // create a new value, perhaps by manipulating the current one 
     var newVal = "???"; 

     // set the new value 
     prop.SetValue(ctx.ObjectInstance, newVal); 

     return base.IsValid(value, ctx); 
    } 
} 
0

아마 당신이 기대하고 무엇을해야하는 패키지입니다 문자열. 검증을 소개하지는 않지만 System.ComponentModel.AnnotationsDado.ComponentModel.Mutations과 함께 사용할 수 있습니다.

public partial class ApplicationUser 
{ 
    [ToLower, RegexReplace(@"[^a-z0-9_]")] 
    public virtual string UserName { get; set; } 
} 

// Then to preform mutation 
var user = new ApplicationUser() { 
    UserName = "[email protected]_speed.01!" 
} 

new MutationContext<ApplicationUser>(user).Mutate(); 

Mutate()에 대한 호출 후, user.UserNamemx_speed01로 변이 될 것입니다.