ASP.NET MVC 2 Validate Nested Objects

和自甴很熟 提交于 2019-12-04 17:18:34

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!