How can I show errors to user on view instead of throwing in MVC?

Viewed 27

I created a validation behaivor but this doesn't show error to user in view. Instead it throws a validation exception in Visual Studio. How can I show errors to the user in view?

 public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
        where TRequest : IRequest<TResponse>
    {
        private readonly IEnumerable<IValidator<TRequest>> _validators;

        public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
        {
            _validators = validators;
        }
        public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            var context = new ValidationContext<TRequest>(request);
            var failures = _validators
                .Select(x => x.Validate(context))
                .SelectMany(x => x.Errors)
                .Where(x=>x !=null)
                .ToList();

            if (failures.Any())
            {
                throw new ValidationException(failures);
            }
            return next();
        }
    }
 public class SaveXValidator : AbstractValidator<SaveXCommand>
    {
        public SaveXValidator()
        {
            RuleFor(x=>x.ImageUrl).NotEmpty().WithMessage("Can't be empty!");
            RuleFor(b => b.StartDate)
            .LessThan(p => p.CreatedDate).WithMessage("error example");
        }
    }
1 Answers

You can show all validations in one place using this in view

 <div asp-validation-summary="All" class="alert alert-danger" role="alert">

If you want to show validation errors at a specific point for each property, you can use this.

<span asp-validation-for="@Model.PropertyName" class="text-danger"></span>
Related