ASP.NET MVC 2 Inspecting Nested Objects

According to the specification, complex child properties (aka "nested objects") are checked only if an input is found for one of the properties of the nested objects.

For example, if Person has properties {string Name, Address HomeAddress} and Address has properties {Street, City}, and the action takes a parameter of type Person, then Person.HomeAddress.Street and Person.HomeAddress.City is only confirmed if the input form had input editors for these nested properties.

Is there a way to force MVC to check nested objects even if no inputs are found for their properties?

Thanks!

+2
source share
1 answer

, DefaultModelBinder

protected virtual void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) {
    Dictionary<string, bool> startedValid = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);

    foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate(null)) {
        string subPropertyName = CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName);

        if (!startedValid.ContainsKey(subPropertyName)) {
            startedValid[subPropertyName] = bindingContext.ModelState.IsValidField(subPropertyName);
        }

        if (startedValid[subPropertyName]) {
            bindingContext.ModelState.AddModelError(subPropertyName, validationResult.Message);
        }
    }

, Person.Address,

<%= Html.HiddenFor(m => m.Address) %>

<%= Html.HiddenFor(m => m.Address.FirstLine) %> //just pick any property

, . , , , , , , :)

, , MVC, , .

+3

All Articles