.NET 4 MVC 2 Validation with annotations warning instead of error

后端 未结 5 1436
轮回少年
轮回少年 2020-12-30 07:53

I am using .NET 4 with MVC 2 for validating with Annotations. Is there a (simple) solution for giving back a warning instead of the error?

5条回答
  •  盖世英雄少女心
    2020-12-30 08:34

    I will first quickly comment that I'm not sure if this is a good idea!

    "Required" attribute has a certain "character" - people expect certain things of it when they include this on their attributes. If you want to use attributes to define this behaviour, try to describe what you're doing more exactly, so instead of your:

    [Required(WarningMessage = "It is recommended to fill out age...")]
    public int Age { get; set; }
    

    I'd have:

    [PreSubmitWarningMessage("It is recommended to fill out age...")]
    public int Age { get; set; }
    

    You can create your own attributes that'll affect how the request is handled, though this won't propagate to client-side validation like the standard MVC attributes do.

    To get this to play nice with MVC, you need to create this as an Action Filter - specifically by implementing the ActionFilterAttribute and overriding the OnActionExecuted method:

    public class PreSubmitWarningMessage : ActionFilterAttribute
    {    
        private string _warningMessage;
    
        public PreSubmitWarningMessage(string warningMessage)
        {
            _warningMessage = warningMessage;
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // stuff you do here will happen before the 
            // controller action is executed.
    
            // you can compare the private warning message 
            // to the metadata in filterContext
        }
    }
    

    You could do a couple of things in here, I'm not sure what best practice would be, but at the hackiest, you have access to the model in filterContext, so you can change the behaviour of your controller action, updating your view model to a certain state if your warning condition (for this case, that the field is required).

    People might make a case for just extending the RequiredAttribute, but I don't think it's correct to say that your new Attribute IS a RequiredAttribute, so inheritence wouldn't be conceptually correct.

提交回复
热议问题