簡體   English   中英

使用ViewModel驗證

[英]Validation with ViewModel

我有一個asp.net mvc3 w / ado.net實體框架做一些驗證。

我已經創建了一個viewmodel

public class id
{


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

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

是否可以添加一些驗證規則,以便l_id必須大於v_id? 驗證應在用戶提交頁面后完成。 怎么做? 任何教程? 此驗證是否需要在控制器中完成或使用部分類? 那里有什么例子嗎?

我一直在使用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(imho)中有一個准錯誤,在某些情況下調用該驗證方法兩次( 比如當這個ViewModel也被用作另一個ViewModel的成員並且被發布時

ValidationResult構造函數的第二個參數是驗證綁定到的屬性的名稱,因此在這種情況下,View中l_ID的ValidatorFor標記將在其中獲得“Bad thing”消息。

ViewModel存在於MVVM模式中,對於您和MVC,您使用Controller,Model和View

是的,您可以在模型中添加DataAnnotation。

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

您需要創建自定義驗證屬性 - 網上有很多幫助。 以下是來自類似依賴屬性的改編。

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

您現在需要做的是找到示例自定義屬性並使其適應以使用上述屬性。

健康警告 - 未經過任何方式測試,可能包含錯誤。

祝好運!

我建議您使用Fluent Validation組件。 它可以與Asp.Net MVC集成,您可以使用流暢的sintaxe輕松添加一些驗證規則。 DataAnnotations也可以正常工作,但我不喜歡,因為它會污染您的域模型或視圖模型。 我想創建一個單獨的職責結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM