是否可以使用某种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(它验证stringlength,regexp等数据)的好处,还有我自定义的绑定器来设置字段值。
我不能只为此编写1个活页夹,因为iam使用EntitiyFramework并与DataAnnotations结合使用会产生这样的结构:
[MetadataType(typeof(MyObjectMetaData))]
public partial class MyObject
{
}
public class MyObjectMetaData
{
[Required]
[StringLength(5)]
public object Storename { get; set; }
}
答案 0 :(得分: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;
}
}
答案 1 :(得分: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();