System.ComponentModel.DataAnnotations v 3.5 で動作する DataAnnotationsModelBinder が必要です。codeplex で
見つけましたが、DataAnnotations の v 0.99 用で、v 3.5 では動作せず、xVal では動作しませんDataAnnotations v 0.99なので、ちょっと立ち往生しています
1 に答える
2
これはかなりナイーブなモデルバインダーですが、あなたが探しているものかもしれません。
public class DataAnnotatedModelBinder : IModelBinder
{
private IModelBinder _defaultBinder = new DefaultModelBinder();
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var boundInstance = _defaultBinder.BindModel(controllerContext, bindingContext);
if (boundInstance != null) {
PerformValidation(boundInstance, bindingContext);
}
return boundInstance;
}
protected void PerformValidation(object instance, ModelBindingContext context)
{
var errors = GetErrors(instance);
if (errors.Any())
{
var rulesException = new RulesException(errors);
rulesException.AddModelStateErrors(context.ModelState, null);
}
}
public static IEnumerable<ErrorInfo> GetErrors(object instance)
{
return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(instance))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(String.Empty), instance);
}
}
于 2009-11-16T20:38:41.003 に答える