0

ルールが常に同じではなく、モデル内の他の属性に依存しているモデルを検証しようとしています。これを行う最善の方法は何ですか?以下の例:

仮定の例 1

MVC 3 で MVVM パターンを使用します。私の (仮想の) ViewModel は次のようになります。

public string OrderType { get; set; }
public string Requestor { get; set; }
public int NumberOfPeanuts { get; set; }
public int NumberOfJellyBeans { get; set; }
public int NumberOfAlmonds { get; set; }

私の見解は基本的に次のようになります。

 @Html.EditorFor(model => model.OrderType ) 
 @Html.EditorFor(model => model.Requestor ) 
 @Html.EditorFor(model => model.NumberOfPeanuts ) 
 @Html.EditorFor(model => model.NumberOfJellyBeans ) 
 @Html.EditorFor(model => model.NumberOfAlmonds )

次のルールに対して「Html.ValidationMessageFor」の結果を返す検証を実装するにはどうすればよいですか。

OrderType = "Peanuts" の場合、NumberOfPeanuts は 0 より大きい必要があり、NumberOfJellyBeans と NumberOfAlmonds は null または 0 でなければなりません。それ以外の場合は、「これはピーナッツのみの注文です」と表示されます。

OrderType = "Sample" の場合、NumberOfPeanuts + NumberOfJellyBeans + NumberOfAlmonds は 30 未満である必要があります。それ以外の場合は、検証メッセージ「サンプルの合計量が不十分です」が表示されます

など...など...

4

2 に答える 2

0

Sam の回答を拡張して、複数のモデル プロパティを使用して検証します。

public class PeanutOrderAttribute : ValidationAttribute, IClientValidatable
{
    private readonly string _peanutsProperty;
    private readonly string _orderTypeProperty;

    public PeanutOrderAttribute(string peanutsPropertyName, string orderTypePropertyName)
    {
        _peanutsProperty = peanutsPropertyName;
        _orderTypeProperty = orderTypePropertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // get target property and value
        var peanutInfo = validationContext.ObjectType.GetProperty(this._peanutsProperty);
        var peanutValue = peanutInfo.GetValue(validationContext.ObjectInstance, null);

        // get compare property and value
        var ordertypeInfo = validationContext.ObjectType.GetProperty(this._orderTypeProperty);
        var ordertypeValue = ordertypeInfo.GetValue(validationContext.ObjectInstance, null);

        // if validation does not pass
        if (ordertypeValue == "Peanuts" && peanutValue < 1){
             return new ValidationResult("Error Message");
        }

        // else return success
        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessageString,
            ValidationType = "PeanutOrder"
        };

        rule.ValidationParameters["peanuts"] = this._peanutsProperty;
        rule.ValidationParameters["ordertype"] = this._orderTypeProperty;

        yield return rule;
    }
}

次に、適切なモデル プロパティに検証タグを配置します。

[PeanutOrder("Peanuts", "OrderType")]
public int Peanuts{ get; set; }

public string OrderType { get; set; }

お役に立てれば!

于 2013-10-03T05:10:40.540 に答える