Is it correct way to use ModelState.Remove to deal with ModelState?

后端 未结 5 842
挽巷
挽巷 2020-12-05 14:17

Im working on a big MVC3 web application and have an annoyance regarding the ModelState.IsValid method.

ModelState is being used in nearly all of my con

5条回答
  •  情话喂你
    2020-12-05 15:01

    If your property is not always required you should not decorate it with [Required].

    A good alternative to do your validation is to implement the interface IValidatableObject.

    For example, let's say that you want to make the field State required only when the country is United States. You could do it that way :

    public class AddressModel : IValidatableObject
    {
        [Required]
        public string Country { get; set; }
        public string State { get; set; }
    
        public IEnumerable Validate(ValidationContext validationContext)
        {
            if(Country == "United States" && String.IsNullOrEmpty(State))
            {
                yield return new ValidationResult("State is required for United States", new [] { nameof(State) });
            }
        }
    }
    

    Note : This kind of validation only works on the server side.

    Other alternatives?

    As mentioned in other answers, it's sometimes a good idea to create 2 or more models if the views and validations are very different.

提交回复
热议问题