1

I have an asp.net mvc3 w/ ado.net entity framework doing some validation.

I have created a viewmodel as such

public class id
{


    [Required]
    public decimal l_ID
    {
        get;
        set;
    }

    [Required]
    public decimal v_ID
    {
        get;
        set;
    }
}

Is it possible to add some set of validation rules so that the l_id must be larger than the v_id? validation should be done once the user has submitted the page. How would this be done? Any tutorials? Does this validation need to be done in the controller or using partial classes? Is there any examples out there

4

4 に答える 4

2

私は IValidatable インターフェイスを使用してきました。これは、カスタム属性の検証に比べてかなり単純です。コードは次のとおりです。

public class id : IValidatableObject
    {
        [Required]
        public decimal l_ID { get; set; }

        [Required]
        public decimal v_ID { get; set; }

        private bool _hasBeenValidated = false;

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {

            if (!_hasBeenValidated)
            {
                // validation rules go here. 
                if (l_ID <= v_ID)
                    yield return new ValidationResult("Bad thing!", new string[] { "l_ID" });
            }

            _hasBeenValidated = true;
        }
    }

ViewModel をパラメーターとして受け取る POST アクションからバインディングが発生すると、Validate メソッドが自動的に呼び出されるので、イベントを関連付ける必要はありません。現在bool _hasBeenValidated、MVC3 (私見) に準バグがあり、場合によってはその検証メソッドを 2 回呼び出すため (この ViewModel が別の ViewModel のメンバーとしても使用され、投稿される場合など)

ValidationResult コンストラクターの 2 番目のパラメーターは、検証がバインドされているプロパティの名前であるため、この場合、ビューの l_ID の ValidatorFor タグは、その「悪いこと」メッセージを受け取ります。

于 2012-10-10T18:16:26.670 に答える
1

ViewModel は MVVM パターンに存在します。コントローラー、モデル、ビューを使用する MVC の場合

はい、モデルに DataAnnotation を追加できます。

リンク: http://www.asp.net/mvc/tutorials/older-versions/models-%28data%29/validation-with-the-data-annotation-validators-cs

于 2012-10-10T17:56:06.837 に答える
1

カスタムの検証属性を作成する必要があります。Web には多くのヘルプがあります。以下は、同様の依存属性からの適応です。

public class GreaterThanOtherAttribute : ValidationAttribute, IClientValidatable
{
    public string DependentProperty { get; set; }

    public GreaterThanOtherAttribute (string dependentProperty)
    {
        this.DependentProperty = dependentProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // get a reference to the property this validation depends upon
        var containerType = validationContext.ObjectInstance.GetType();
        var field = containerType.GetProperty(this.DependentProperty);

        if (field != null)
        {
            // get the value of the dependent property
            var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);

            // compare the value against the target value
            if ((dependentvalue == null && this.TargetValue == null) ||
                (dependentvalue != null && dependentvalue < this.TargetValue)))
            {
                // match => means we should try validating this field
                return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName });
            }
        }

        return ValidationResult.Success;
    }

次に、モデルを装飾します。

public class id           
{      
    [Required]           
    public decimal l_ID           
    {           
        get;           
        set;           
    }           

    [Required]   
    [GreaterThanOtherAttribute("l_ID")]        
    public decimal v_ID           
    {           
        get;           
        set;           
    }           
}     

ここで行う必要があるのは、カスタム属性の例を見つけて、上記を使用するように調整することです。

健康に関する警告 - これはまったくテストされておらず、おそらくエラーが含まれています。

幸運を!

于 2012-10-10T18:09:02.743 に答える
0

FluentValidationコンポーネントを使用することをお勧めします。Asp.Net MVCと統合でき、流暢な構文を使用していくつかの検証ルールを簡単に追加できます。DataAnnotationsも正常に機能しますが、ドメインモデルまたはビューモデルを汚染するため、私は好きではありません。私は別の責任構造を作成するのが好きです。

于 2012-10-10T18:05:22.067 に答える