DataAnnotation Validations and Custom ModelBinder

后端 未结 3 1383
情话喂你
情话喂你 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:05

    I had the same issue. The answer is instead of overriding BindModel() in your custom model binder, override CreateModel()...

    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, System.Type modelType)
    {
        if (modelType == typeof(IPhoto))
        {
            IPhoto photo = new PhotoImpl();
            // snip: set properties of photo to bound values
            return photo;
        }
    
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
    

    You can then let the base BindModel class do its stuff with validation :-)

提交回复
热议问题