我希望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] = ...
}
}
答案 0 :(得分:1)
你可以到MVC的来源
http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/DefaultModelBinder.cs
并重写DefaultModelBinder