public void Bind(PropertyInfo property, BindingContext bindingContext) { var value = bindingContext.GetValue(property.Name); if (value != null) return; // boolean values like checkboxes don't appear unless checked, so set false by default if (property.PropertyType == typeof(bool) && property.CanWrite) { property.SetValue(bindingContext.Target, false, null); } }
public virtual void UpdateFrom(BindingContext bindingContext) { foreach (var property in bindingContext.Target.GetType().GetProperties()) { try { foreach (var binder in propertyBinders) { binder.Bind(property, bindingContext); } } catch (Exception exception) { if (exception.InnerException is FormatException || exception.InnerException is IndexOutOfRangeException) { string key = BuildKeyForModelState(property, bindingContext.ObjectPrefix); bindingContext.AddModelError(key, bindingContext.AttemptedValue, "Invalid value for {0}".With(property.Name)); bindingContext.ModelStateDictionary.SetModelValue(key, new ValueProviderResult(bindingContext.AttemptedValue, bindingContext.AttemptedValue, CultureInfo.CurrentCulture)); } else if (exception is ValidationException) { string key = BuildKeyForModelState(property, bindingContext.ObjectPrefix); bindingContext.AddModelError(key, bindingContext.AttemptedValue, exception.Message); bindingContext.ModelStateDictionary.SetModelValue(key, new ValueProviderResult(bindingContext.AttemptedValue, bindingContext.AttemptedValue, CultureInfo.CurrentCulture)); } else if (exception.InnerException is ValidationException) { string key = BuildKeyForModelState(property, bindingContext.ObjectPrefix); bindingContext.AddModelError(key, bindingContext.AttemptedValue, exception.InnerException.Message); bindingContext.ModelStateDictionary.SetModelValue(key, new ValueProviderResult(bindingContext.AttemptedValue, bindingContext.AttemptedValue, CultureInfo.CurrentCulture)); } else { throw; } } } if (!bindingContext.ModelStateDictionary.IsValid) { throw new ValidationException("Bind Failed. See ModelStateDictionary for errors"); } }