Uppercase attribute that converts the input to uppercase

前端 未结 4 1972
长发绾君心
长发绾君心 2020-12-18 01:36

I am working in MVC4 and want to define a model using an Uppercase attribute. The idea would be that the presence of the Uppercase attribute would cause the mod

4条回答
  •  情书的邮戳
    2020-12-18 02:25

    You're right, ValidationAttribute is not the right fit. It seems like doing this at the Model Binding stage would be a better idea. See this article for a detailed explanation of how to customize this behavior.

    Based on the information provided there, I believe you should be able to create an attribute based on CustomModelBinderAttribute like this:

    [AttributeUsage(AttributeTargets.Property)]
    public class UppercaseAttribute : CustomModelBinderAttribute
    {
        public override IModelBinder GetBinder()
        {
            return new UppercaseModelBinder();
        }
    
        private class UppercaseModelBinder : DefaultModelBinder
        {
            public override object BindModel(
                ControllerContext controllerContext,
                ModelBindingContext bindingContext)
            {
                var value = base.BindModel(controllerContext, bindingContext);
                var strValue = value as string;
                if (strValue == null)
                    return value;
                return strValue.ToUpperInvariant();
            }
        }
    }
    

    I have not tested this. Let me know if it works or not.

提交回复
热议问题