1

is it possible to use some kind of Multibinders, like this?

[Authorize]
[AcceptVerbs("POST")]
public ActionResult Edit([CustomBinder]MyObject obj)
{
   ///Do sth.
}

When i ALSO have configured a default binder like this:

    protected void Application_Start()
    {
        log4net.Config.XmlConfigurator.Configure();
        RegisterRoutes(RouteTable.Routes);

        ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();
    }

What i want is to have the benefits of the DataAnnotationsBinder ( which validates the data for stringlength, regexps, etc ) and additionally my custom binder which sets the field values.

I can't write only 1 binder for this, as iam using the EntitiyFramework and in combination with the DataAnnotations it results in contstruct like this:

   [MetadataType(typeof(MyObjectMetaData))]
   public partial class MyObject
   {
   }


   public class MyObjectMetaData
   {
    [Required]
    [StringLength(5)]
    public object Storename { get; set; }
   }

2 Answers 2

1

You can try calling the default model binder in your custom model binder.

public class CustomBinder : IModelBinder {
    public object BindModel(ControllerContext controllerContext, 
    ModelBindingContext bindingContext) {
         MyObject o = (MyObject)ModelBinders.Binders
             .DefaultBinder.BindModel(controllerContext, bindingContext);
         //Your validation goes here.
         return o;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Why don't you just inherit from DataAnnotationsModelBinder?

public class MyBinder : DataAnnotationsModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        MyModel obj = (MyModel)base.BindModel(controllerContext, bindingContext);
        //Do your operations
        return obj;
    }
}

ModelBinders.Binders[typeof(MyModel)] = new MyBinder();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.