ASP.NET MVC如何找到哪个属性是错误的

时间:2013-11-25 07:09:49

标签: c# asp.net-mvc modelbinders model-validation

我希望ModelBinder出错,自动在ModelState中附加错误代码。 所以我扩展了默认属性以添加属性。(关于RequiredAttribute,RangeAttribute等),如:

//new Attribute
public class TestRequiredAttribute : RequiredAttribute
{
    public int ErrorCode { get; set; }
}

但我不知道,我怎么知道ModelBinder中哪个属性出错?

public class TestModelBinder : DefaultModelBinder
{
      protected override void SetProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext,
System.ComponentModel.PropertyDescriptor propertyDescriptor,
object value)
    {
          //the error was happend in here
          base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);

          //in here to find which attribute has been error?
          to find attribute and to get ErrorCode then 
          bindingContext.ModelState[modelStateName+code] = ...
    }
}

1 个答案:

答案 0 :(得分:1)