ASP.NET MVC 2验证嵌套对象 [英] ASP.NET MVC 2 Validate Nested Objects

查看:212
本文介绍了ASP.NET MVC 2验证嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据规范,如果输入被发现嵌套对象的属性之一(又名嵌套对象),复杂的子属性只验证。

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.

例如,如果人具有属性{字符串名称,地址是homeAddress}和地址具有属性{街道,城市}和行动接受Person类型的参数,然后Person.HomeAddress.Street和Person.HomeAddress.City只如果输入的形式有那些嵌套属性输入编辑的验证。

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.

有没有什么办法可以强制MVC验证嵌套的对象,即使没有发现他们的财产投入?

Is there any way I can force MVC to validate nested objects, even if inputs are not found for their properties?

谢谢!

推荐答案

我不这么认为,因为验证在以下code做 DefaultModelBinder

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);
        }
    }

您可以尝试通过使用一个隐藏的表单字段的Person.Address财产像这样

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) %>

<%= 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 :)

另外,您可以尝试编写自己的模型绑定,但是从我的经验,如果你开始违背MVC框架的粮食会回来咬你。

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

这篇关于ASP.NET MVC 2验证嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆