views:

356

answers:

2

Hi,

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; }
   }
A: 

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;
    }
}
çağdaş
+1  A: 

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();
LukLed