在基于数据注释的模型上应用字符串扩展方法?

时间:2015-02-26 19:52:01

标签: c# asp.net-mvc data-annotations

这可能是不可能的,但如果可能的话,它将为我节省大量的大项目时间。

假设我有一个格式化字符串的扩展方法。扩展方法的实现并不重要,但想象一下:

public static string AddPrefix(this string input) {
       return string.Format("{0}{1}", "pre_", input);
}

我希望能够做到这一点,为我希望应用扩展方法的模型中的字段添加数据注释。我不想验证用户输入以匹配扩展方法的格式,但我想在为其应用的任何字段提交数据之前应用扩展方法。

例如,我可能有:

public class Person {

    [Prefix]
    public string Forename {get;set;}
}

然后我想在将模型提交到数据库或Web服务之前将扩展方法应用于forename。

我想象这是不可能的,所以如果没有人可以指出应用扩展方法的最佳方式 - 在我的域模型中可能有多达50个字段分布在各种类中。

3 个答案:

答案 0 :(得分:1)

我搜索了一下,发现这个answer表示你基本上不应该修改属性的属性值。这是错的。但这里是some way

public class PrefixAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
       //try to modify text
            try
            {
                validationContext
                .ObjectType
                .GetProperty(validationContext.MemberName)
                .SetValue(validationContext.ObjectInstance, string.Format("{0}{1}", "pre_", value.ToString()), null);
            }
            catch (System.Exception)
            {                                    
            }

        //return null to make sure this attribute never say iam invalid
        return null;
    }
}

答案 1 :(得分:1)

一种选择是利用面向方面编程。

这不需要扩展方法。

PostSharp在.NET开发中很受欢迎。

答案 2 :(得分:0)

听起来你想要创建自定义数据注释,就是这种情况吗?

如果是这样,那就有可能。