简体   繁体   English

如何将自定义错误消息返回给View?

[英]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.

相关问题 如何验证多个数据注释并在视图中返回一条错误消息 - How to validate multiple data annotations and return one error message in view 如何返回 http 错误状态代码以及 class 中的自定义消息 - How to return http error status code along with custom message in a class 如何使用自定义消息返回 401? - How to return a 401 with a custom message? 如何使用自定义消息返回文件 - How to return File with custom Message 如何从自定义 AuthorizeAttribute 返回自定义消息? - How to return custom message from custom AuthorizeAttribute? 在WCF http服务中返回自定义错误消息 - Return a custom error message in WCF http service 当includeExceptionDetailInFaults =“ false”时返回自定义错误消息 - Return custom error message when includeExceptionDetailInFaults=“false” ASP.Net MVC错误验证-将自定义视图模型传递给视图时如何显示验证消息 - ASP.Net MVC Error Validation - How to display validation message when passing a custom view model to a view 如何返回特定的错误信息 - how to return specific error message 如何在视图中返回 HTTP BadResponse 消息? - How to return HTTP BadResponse message in the View?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM