Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Inner
- {
- [Range(10, 20)]
- public int InnerProperty { get; set; }
- }
- public class Outer
- {
- public Outer()
- {
- Inner = new Inner();
- }
- public Inner Inner { get; set; }
- [Range(10, 20)]
- public int OuterProperty { get; set; }
- }
- public class TestModelBinder : DefaultModelBinder
- {
- public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
- {
- if (bindingContext.ModelType == typeof(Outer))
- {
- Outer outer = new Outer();
- //Three different tests here:
- //outer.OuterProperty = 15;
- //outer.Inner.InnerProperty = 5; - this is suposed to be an error, but its not
- // For above configuration, ModelState.Keys.Count = 0
- //outer.OuterProperty = 5;
- //outer.Inner.InnerProperty = 5; - this is suposed to be an error, but its not
- // For above configuration, ModelState.Keys.Count = 1 ( OuterProperty)
- outer.OuterProperty = 15;
- outer.Inner.InnerProperty = 15;
- // For above configuration, ModelState.Keys.Count = 0
- ModelBindingContext newBindingContext = new ModelBindingContext()
- {
- ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
- () => outer,
- typeof(Outer)
- ),
- ModelState = bindingContext.ModelState,
- ValueProvider = bindingContext.ValueProvider
- };
- return base.BindModel(controllerContext, newBindingContext);
- }
- else
- {
- return base.BindModel(controllerContext, bindingContext);
- }
- }
- }
- ModelBinders.Binders[typeof(Outer)] = new TestModelBinder();
- [HttpPost]
- public ActionResult Test(Outer tme)
- {
- bool isValid = ModelState.IsValid;
- return View();
- }
Add Comment
Please, Sign In to add comment