Conditionally validating portions of an ASP.NET MVC Model with DataAnnotations?

后端 未结 7 1953
不思量自难忘°
不思量自难忘° 2020-12-30 10:12

I have certain panels on my page that are hidden under certain circumstances.

For instance I might have a \'billing address\' and \'shipping address\' and I dont wan

7条回答
  •  萌比男神i
    2020-12-30 10:51

    For the CheckoutModel I am using this approach (most fields hidden):

    [ModelBinder(typeof(CheckoutModelBinder))]
    public class CheckoutModel : ShoppingCartModel
    {        
        public Address BillingAddress { get; set; }
        public Address ShippingAddress { get; set; }
        public bool ShipToBillingAddress { get; set; }
    }
    
    public class Address
    {
        [Required(ErrorMessage = "Email is required")]
        public string Email { get; set; }
    
        [Required(ErrorMessage = "First name is required")]
        public string FirstName { get; set; }
    
        [Required()]
        public string LastName { get; set; }
    
        [Required()]
        public string Address1 { get; set; }
    }
    

    The custom model binder removes all ModelState errors for fields beginning with 'ShippingAddress' if it finds any. Then 'TryUpdateModel()' will return true.

        public class CheckoutModelBinder : DefaultModelBinder
        {
            protected override void OnModelUpdated(ControllerContext controllerContext,
                                                   ModelBindingContext bindingContext) {
    
                base.OnModelUpdated(controllerContext, bindingContext);
    
                var model = (CheckoutModel)bindingContext.Model;
    
                // if user specified Shipping and Billing are the same then 
                // remove all ModelState errors for ShippingAddress
                if (model.ShipToBillingAddress)
                {
                    var keys = bindingContext.ModelState.Where(x => x.Key.StartsWith("ShippingAddress")).Select(x => x.Key).ToList();
                    foreach (var key in keys)
                    {
                        bindingContext.ModelState.Remove(key);
                    }
                }
            }    
        }
    

    Any better solutions?

提交回复
热议问题