我有ViewModel
:
public string Address { get; set; }
[DisplayName("Do you want Reward?")]
public bool IsReward { get; set; }
[Range(0,int.MaxValue,ErrorMessage="Please enter integer number")]
[DisplayName("Reward")]
public int Reward { get; set; }
默认情况下,在视图中IsReward
属性未选中,当用户选中Isreward
并发布视图时,如果Reward
文本框为空,则向用户显示错误消息“请输入奖励”。
如何使用DataAnnotation
验证它?
答案 0 :(得分:0)
尝试以下代码。如果IsReward
为真且Reward
文本框值为零,则会显示错误消息。
[RewardValidation]
public class RewardModel
{
public string Address { get; set; }
[DisplayName("Do you want Reward ؟")]
public bool IsReward { get; set; }
[Range(0, int.MaxValue, ErrorMessage = "Please enter integer number")]
[DisplayName("Reward")]
public int Reward { get; set; }
}
public class RewardValidation : ValidationAttribute
{
public override bool IsValid(object value)
{
RewardModel app = value as RewardModel;
if (app.IsReward && app.Reward==0)
{
ErrorMessage = "please enter Reward";
return false;
}
return true;
}
}
并在视图中加入@Html.ValidationSummary(true)
以显示消息