1

このように、ある種のマルチバインダーを使用することは可能ですか?

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

私もこのようにデフォルトのバインダーを設定した場合:

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

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

私が望むのは、DataAnnotationsBinder (stringlength、regexps などのデータを検証する) と、さらにフィールド値を設定するカスタム バインダーの利点を得ることです。

EntitiyFramework を使用し、DataAnnotations と組み合わせて、次のようなコンストラクトになるため、このためにバインダーを 1 つだけ作成することはできません。

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


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

2 に答える 2

1

カスタム モデル バインダーで既定のモデル バインダーを呼び出すことができます。

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;
    }
}
于 2010-01-17T11:20:47.683 に答える
1

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();
于 2010-01-17T12:52:18.037 に答える