[英]How to return custom error message to View?
I have created a datechecker class, which returns an error if the selected date is in the past: 我创建了一个datechecker类,如果所选的日期是过去的日期,它将返回一个错误:
public class ValidateDateRange : ValidationAttribute
{
public DateTime FirstDate = DateTime.Today;
//public DateTime SecondDate { get; set; }
private const string DefaultIncorrectDateMessage = "The date you entered is incorrect. Please try again";
public string DateInPastMessage { get; set; }
//public string DateNotInRangeMessage { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// your validation logic
if (Convert.ToDateTime(value) >= DateTime.Today)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(DateInPastMessage ?? DefaultIncorrectDateMessage);
}
}
}
This is my view: 这是我的看法:
[ValidateDateRange(DateInPastMessage = "Your date is in the past. Please select a date starting from today!")]
[DataType(DataType.Date)]
public DateTime ArrivalDate { get; set; }
This works correctly, however the DateInPastMessage
is now returned as a debug message, when the application fails on db.SaveChanges(). 这工作正常,但是DateInPastMessage
现在返回调试消息,当应用程序上db.SaveChanges失败()。
I want to have this message in the View, like a normal error message: 我希望在视图中有此消息,就像普通的错误消息一样:
How can I send my custom error message to the View? 如何将自定义错误消息发送到视图? Can this be done without creating custom jquery validation in every view where I have a datepicker field? 是否可以在没有Datepicker字段的每个视图中创建自定义jquery验证的情况下完成此操作?
You should set the ErrorMessage
in ValidationAttribute
. 您应该在ValidationAttribute
设置ErrorMessage
。 I think that's why it's not showing. 我认为这就是为什么它不显示。
ErrorMessage = DefaultIncorrectDateMessage;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.