1

私はasp.net mvc 2 Webアプリケーションに取り組んでいます。私は3つのプロパティを持つモデルを持っています:

[IsCityInCountry("CountryID", "CityID"]
public class UserInfo
{
    [Required]
    public int UserID { get; set; }

    [Required]
    public int CountryID { get; set; }

    [Required]
    public int CityID { get; set; }
}

「必須」のプロパティ属性が 1 つと、クラス レベルに 1 つの属性があります。

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class IsCityInCountry : ValidationAttribute
{
    public IsCityInCountry(string countryIDProperty, string cityIDProperty)
    {
        CountryIDProperty = countryIDProperty;
        CityIDProperty = cityIDProperty;
    }
    public string CountryIDProperty { get; set; }
    public string CityIDProperty { get; set; }

    public override bool IsValid(object value)
    {
        var properties = TypeDescriptor.GetProperties(value);

        var countryID = properties.Find(CountryIDProperty, true).GetValue(value);
        var cityID = properties.Find(CityIDProperty , true).GetValue(value);

        int countryIDInt;
        int.TryParse(countryID.ToString(), out countryIDInt);

        int cityIDInt;
        int.TryParse(cityID.ToString(), out cityIDInt);

        if (CountryBusiness.IsCityInCountry(countryIDInt, cityIDInt))
        {
            return true;
        }

        return false;
    }
}

ビューにフォームを投稿し、CountryID が入力されていない場合、ModelState ディクショナリにその問題に関するエラーがあります。他の属性は無視されます ("IsCityInCountry")。選択した国にない CountryID と CityID を選択すると、それに関する適切な検証メッセージが表示され、ModelState には別のキー ("") があります。アドバンテージにはプロパティ属性とクラス属性があることを理解しています。私の質問; 関連する属性の種類 (クラスまたはプロパティ属性) に関係なく、すべての検証メッセージを同時に取得する方法はありますか? 前もって感謝します。

4

1 に答える 1

1

プロパティ レベルの検証エラーがある場合、ASP.NET MVC はクラス レベルの検証を実行しません。ブラッド・ウィルソンは彼のブログ記事でこれを説明しています:

本日、検証システムを入力検証からモデル検証に変換する MVC 2 への変更をコミットしました。

これが意味することは、モデル バインド中にそのオブジェクトに少なくとも 1 つの値がバインドされている場合、常にそのオブジェクトに対してすべてのバリデータを実行するということです。最初にプロパティ レベルのバリデーターを実行し、それらがすべて成功した場合は、モデル レベルのバリデーターを実行します。

ASP.NET MVC アプリケーションでさらに高度な検証を実行する場合は、先に進んでFluentValidation.NETをチェックアウトすることをお勧めします。宣言型の検証は、高度な検証シナリオでは単純に当てはまりません。

于 2011-10-16T16:33:38.417 に答える