如何使用流畅的验证将来自 asp.net 网络应用程序的输入错误输入到我的 Index.cshtml 视图中?

How to get the input errors from asp.net web app into my Index.cshtml view using fluent validation?

我正在处理需要对输入字段进行验证的 Web 表单。我已经使用 AngularJS 实现了这一点(该应用程序也使用 AngularJS),但现在我需要使用 Fluent Validation 更具体地使用 ASP.NET 获取这些错误输入消息。现在我得到的结果是 JSON,比如 Key: CompanyName Message: "Error message appear",但我需要它的格式是 CompanyName: Error message appear。第 2 步是 HTML 中的输入字段要打印的消息。如果有人可以帮助我,我将不胜感激。提前谢谢你。

我的 UserValidator 文件,包含 Fluent Validation

public class UserValidator : AbstractValidator<UserViewModel>
    {
        public UserValidator()
        {
            RuleFor(p => p.CompanyName)
                .NotNull().WithMessage("This field is required")
                .Length(2, 30).WithMessage("Please enter a valid name!");

            RuleFor(p => p.Name)
                .NotNull().WithMessage("This field is required")
                .Length(2, 30).WithMessage("Please enter a valid name!");


            RuleFor(p => p.Surname)
                .NotNull().WithMessage("This field is required")
                .Length(2, 30).WithMessage("Please enter a valid name!");


            RuleFor(p => p.Phone)
                .NotNull().WithMessage("This field is required")
                .Length(5, 20).WithMessage("No less than 5 numbers, and no more than 20");

            RuleFor(p => p.EMail)
                .EmailAddress().WithMessage("Please enter valid Email address")
                .NotNull().WithMessage("This field is required");

            RuleFor(p => p.Country)
           .NotNull().WithMessage("Please select a country");
        }
       

    }

现在这是我的视图模型的代码

namespace ViewModel
{
    [Serializable]
    [Validator(typeof (UserValidator))]

    public class UserViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string CompanyName { get; set; }
        public string Phone { get; set; }
        public string Country { get; set; }
        public string EMail { get; set; }
        public string Note { get; set; }
    }
}

这是我的包含所有逻辑的 AppService 文件:

 public bool Register(UserViewModel model)
        {

            var validator = new UserValidator();
            ValidationResult results = validator.Validate(model);

            if (!results.IsValid)
            {
                var errors = results.Errors
                    .Select(x => new ValidationRecord(x.PropertyName, x.ErrorMessage)).ToList();

                throw new CustomException(errors);

}

return true;
}

这是我的 ValidationRecord 和 CustomValidationException。

    public class ValidationRecord
    {
        public ValidationRecord()
        {

        }
        public ValidationRecord(string key, string message)
        {
            Key = key;
            Message = message;
        }

        public string Key { get; }
        public string Message { get; }
    }
    public class CustomValidationException : Exception
    {
        public CustomValidationException()
            : base()
        {
        }

        public CustomValidationException(string message, params object[] args)
            : base(string.Format(message ?? string.Empty, args))
        {
        }

    }
    public class CustomException : Exception
    {
        public List<ValidationRecord> Errors { get; set; }

        public CustomException()
            : base()
        {
        }

        public CustomException(List<ValidationRecord> errors)
        {
            Errors = errors;
        }
    }
}

我的主页Ctrl:

[HttpPost]
public JsonResult Register(UserViewModel model)
        {
            return ActionWrapper.InvokeControlledAction<JsonResult>(x =>
            {
                return Json(_countryService.Register(model));
            });
        }

现在我的 app.js 文件:

app.factory('contactFormService', ['$http', function ($http) {
    var dataFactory = {};

    dataFactory.register = function (model) {
        return $http.post("Home/Register/", {model: model});
    };
    return dataFactory;

}]);

app.controller("MainCtrl", ['$scope', '$http', 'contactFormService', function ($scope, $http, contactFormService) {

    $scope.initModel = function () {
        $scope.model = {
            CompanyName: '',
            Name: '',
            Surname: '',
            Phone: '',
            Note: '',
            Country: '',
            EMail: '',
            Errors: []
        };
        $scope.countries = [];
        $scope.showResult = false
    };
    $scope.initModel();


    

    $scope.submitForm = function () {
        contactFormService.register($scope.model)
            .then(function (response) {
                $scope.showResult = true;
            }, function (error) {
                    $scope.model.Errors = error.data
            });

我设法回答了我自己的问题,因此此代码适用于将来会遇到此问题的所有人。问题主要是我弄错了功能。这是假设您将错误验证消息存储到数组中的函数。这是代码希望它对某人有用。

$scope.eMessages = function (data) {
        data.ValidationErrors = {};
        angular.forEach(data.Errors, function (key, value) {
            if (key.Key != null) {
                data.ValidationErrors[key.Key] = key.Message;
            }
       
        });
        return data;
    };