1

是否可以使用某种 Multibinders,像这样?

[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 的好处(它验证字符串长度、正则表达式等的数据)以及设置字段值的自定义活页夹。

我不能为此只编写 1 个活页夹,因为 iam 使用 EntitiyFramework 并与 DataAnnotations 结合使用它会导致如下构造:

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


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

2 回答 2

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 回答
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 回答