开发者

List<string> PropertyName isn't showing up in modelState.errors

Imagine, a model like this:

[AddressValidation]
public AddressType[] Address { get; s开发者_StackOverflow中文版et; }

    internal class AddressValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        //Assume we are valid
        var isValid = true;

        //Cast to something useful
        var addresses = (AddressType[])value;

        var defaultAddresses = addresses.Count(a => a.AddressCode == AddressCodeEnum.@default);

        if (defaultAddresses == 0)
        {
            ErrorMessage = "One address must be the default address";
            isValid = false;
        }
        else if (defaultAddresses > 1)
        {
            ErrorMessage = "Only one address can be the default address";
            isValid = false;
        }

        //Return the result
        return isValid;
    }
}

When the model is validated by the controller, any of the subordinate addresses are properly validated and any errors are returned as modelstate errors. However, the custom attribute's error is never added to modelstate, even though it validates false.

It seems as if this should work, the validation is called and I can step through it - it just never gets added to modelstate.

Ideas?


Two different checks are taking place, and you want to return one of two different errors, so this should be split into two attributes. In particular, you cannot set the ErrorMessage property from within the IsValid() method itself. These attribute instances must be immutable. The first time the ErrorMessage property is read by the framework, that's it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜