DataAnnotation Validations and Custom ModelBinder

后端 未结 3 1393
情话喂你
情话喂你 2020-12-30 14:00

I\'ve been running some experiments with ASP.NET MVC2 and have run into an interesting problem.

I\'d like to define an interface around the objects that will be used

3条回答
  •  梦谈多话
    2020-12-30 15:07

    After inspecting the source for System.Web.MVC.DefaultModelBinder, it looks like this can be solved using a slightly different approach. If we rely more heavily on the base implementation of BindModel, it looks like we can construct a PhotoImpl object while still pulling the validation attributes from IPhoto.

    Something like:

    public class PhotoModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType == typeof(IPhoto))
            {
                ModelBindingContext newBindingContext = new ModelBindingContext()
                {
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
                        () => new PhotoImpl(), // construct a PhotoImpl object,
                        typeof(IPhoto)         // using the IPhoto metadata
                    ),
                    ModelState = bindingContext.ModelState,
                    ValueProvider = bindingContext.ValueProvider
                };
    
                // call the default model binder this new binding context
                return base.BindModel(controllerContext, newBindingContext);
            }
            else
            {
                return base.BindModel(controllerContext, bindingContext);
            }
        }
    }
    

提交回复
热议问题