开发者

ASP.NET MVC 2 Validate Nested Objects

开发者 https://www.devze.com 2023-01-09 01:52 出处:网络
According to the spec, complex child properties (aka \"nested objects\") are validated only if an input is found for one of the nested object\'s properties.

According to the spec, complex child properties (aka "nested objects") are validated only if an input is found for one of the nested object's properties.

For example, if Person has properties { string Name, Address HomeAddress } and Address has properties { Street, City }, and an action accepts parameter of type Person, then Person.HomeAddress.Street and Person.HomeAddress.City are only validated if the input form had input editors for those nested properties.

Is the开发者_JAVA技巧re any way I can force MVC to validate nested objects, even if inputs are not found for their properties?

Thanks!


I don't think so, since the validation is done with the following code in 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);
        }
    }

You could try tricking the model binder by using a hidden form field for the Person.Address property like this

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

or

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

And that may kick off the model binder to do a validation. Although if this does work, then you will not beable to put in a value, since it is a hidden form field, but I believe this is what you want :)

Alternatively you could try and write your own model binder, but from my experience if you start to go against the grain of the MVC framework it will come back to bite you

0

精彩评论

暂无评论...
验证码 换一张
取 消