【问题标题】:How to send validation error message to view with Fluent Validation如何发送验证错误消息以使用 Fluent Validation 进行查看
【发布时间】:2021-08-03 06:23:53
【问题描述】:

目前正在向我的项目添加验证,我遇到了 Fluent Validation,我创建了这样的验证器:

using Dealership.App.Models.CarBrand;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Dealership.App.FluentValidation
{
    public class CarBrandValidator : AbstractValidator<CreateCarBrandViewModel>
    {
        public CarBrandValidator()
        {
            RuleFor(brand => brand.CarBrandName).NotNull()
                .WithMessage("Car Brand needs to have a name");
        }
    }
}

正如文档所建议的那样,我在启动文件中对其进行了如下配置:

    services.AddMvc()
        .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());

现在这是我应用验证的控制器中的操作方法

public async Task<IActionResult> CreatePost(CreateCarBrandViewModel newBrand) 
{
    if(ModelState.IsValid)
    {
        var response = await _mediator.Send(new CreateCarBrandCommand(newBrand));
        if (response)
        {
            this._unitOfWork.Commit();
        }

        return RedirectToAction("Index");
    }

    return RedirectToAction("Create");
}

这是我的观点:

@model Dealership.App.Models.CarBrand.CreateCarBrandViewModel

<div asp-validation-summary="ModelOnly"></div>
<form asp-action="CreatePost" method="POST">
    <div class="form-group">
        <label for="BrandName">Brand Name</label>
        <input asp-for="CarBrandName" class="form-control col-4" id="BrandName" placeholder="Enter Car Brand name" />
        <span asp-validation-for="CarBrandName"></span>
    </div>
    <button type="submit" class="btn btn-primary">Create</button>
</form>

事情是这样的,我的验证工作 50%,我的意思是如果我在验证器中指定的字段为空,验证工作在方面,它将再次重定向回同一页面,一切都很好。 但是我想显示我在验证器中设置的错误消息,我已经尝试了很多东西并阅读了很多东西,如果有人可以提供帮助,那就太棒了

提前致谢

【问题讨论】:

  • 可以分享一下吗?
  • 我确实可以,见上

标签: c# asp.net-core fluentvalidation


【解决方案1】:

好吧,我找到了答案,这是一个简单的 RedirecToAction,因为当验证失败时我需要返回创建视图。 最初我有return RedirectToAction({view-name}),我需要做 return View({view-name}).

【讨论】:

    猜你喜欢
    • 2011-12-26
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多