2014-02-21 57 views
0

我的模型看起來像MVC驗證功能無法正常工作

public class MPariData : IValidatableObject 
{ 
    public int moneyObtain { get; set; } 
    public string IBAN { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     var fields = new[] { "IBAN" }; 

     if (moneyObtain == 2) 
     { 
      yield return new ValidationResult("Required field" ,fields); 
     } 
    } 
} 

我想如果要需要moneyObtains == 2IBAN場。 我的看法如下:

<div class="col-lg-10"> 
    @Html.TextBoxFor(model => model.IBAN, new { @class = "form-control" }) 
    @Html.ValidationMessageFor(model => model.IBAN) 
</div> 

但是沒有成功。我的驗證消息未出現,並且在我的控制器ModelState中始終有效。

任何想法?

回答

0

我想這一點,和它的工作: 對於模型:

public int moneyObtain { get; set; } 
    public string IBAN { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     List<ValidationResult> result = new List<ValidationResult>(); 

     if (moneyObtain == 2) 
     { 
      result.Add(new ValidationResult("Required field", new string[] { "IBAN" })); 
      return result; 
     } 

...

對於視圖: ....

<tr> 
     <td>@Html.LabelFor(m => m.moneyObtain)</td> 
     <td>@Html.EditorFor(m => m.moneyObtain)</td> 
     <td>@Html.ValidationMessageFor(m => m.moneyObtain)</td> 
</tr> 
<tr> 
     <td>@Html.LabelFor(m => m.IBAN)</td> 
     <td>@Html.EditorFor(m => m.IBAN)</td> 
     <td>@Html.ValidationMessageFor(m => m.IBAN)</td> 
</tr> 

...