开发者

ASP.NET MVC: Multiple model binding

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

[Authorize]
[AcceptVerbs("POST")]
public ActionResult Edit([CustomBinder]MyObjec开发者_JAVA技巧t 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; }
   }


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜