我的模型看起来像
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 == 2
,IBAN
字段,我想要。
我的观点如下:
<div class="col-lg-10">
@Html.TextBoxFor(model => model.IBAN, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.IBAN)
</div>
但没有成功。我的验证消息没有出现,而且我的控制器ModelState
始终有效。
有什么想法吗?
答案 0 :(得分: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>
...