首页 > 解决方案 > 如何使用流利的验证将来自 asp.net Web 应用程序的输入错误输入到我的 Index.cshtml 视图中?

问题描述

我正在开发一个需要对输入字段进行验证的 Web 表单。我已经通过 AngularJS(该应用程序也使用 AngularJS)实现了这一点,但现在我需要更具体地使用 Fluent Validation 通过 ASP.NET 获取这些错误输入消息。现在我得到 JSON 格式的结果,如 Key: CompanyName Message: "Error message appear",但我需要 CompanyName: Error message 的格式。第二步是由 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
            });

标签: .netangularjsfluentvalidation

解决方案


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

$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;
    };

推荐阅读