如何向客户端呈现错误? AngularJS / WebApi ModelState

时间:2014-04-15 14:28:06

标签: angularjs validation asp.net-web-api modelstate

我正在为后端构建一个带WebApi的AngularJS SPA应用程序。我在服务器上使用属性进行模型验证,如果验证失败,这就是我从ModelState返回的内容。

     {"Message":"The request is invalid.","ModelState":{"model.LastName":["Last Name must be at least 2 characters long."]}}

如何使用AngularJS将其呈现给客户端?

      //Save User Info
    $scope.processDriverForm = function(isValid) {
        if (isValid) {
            //set button disabled, icon, text
            $scope.locked = true;
            $scope.icon = 'fa fa-spinner fa-spin';
            $scope.buttonText = 'Saving...';
            $scope.submitted = true;
            $scope.formData.birthDate = $scope.formData.birthMonth + '/' + $scope.formData.birthDay + '/' + $scope.formData.birthYear;
            $http({
                    method: 'POST',
                    url: 'api/Account/Register',
                    data: $.param($scope.formData),
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
                })
                .success(function (data) {
                    console.log(data);
                    toastr.success('User ' + $scope.formData.username + ' created!');
                    $scope.userForm.$setPristine();
                    $scope.formData = {};
                    //reset the button
                    $scope.locked = false;
                    $scope.icon = '';
                    $scope.buttonText = 'Save';
                    //reset validation submitted
                    $scope.submitted = false;
                })
                .error(function (data, response) {
                    console.log(data);
                    toastr.error('Ooops! There was an error creating the user. Try again and if the problem persists, contact Support.');
                    //reset the button
                    $scope.locked = false;
                    $scope.icon = '';
                    $scope.buttonText = 'Save';
                    $scope.submitted = false;

                    var resp = {};

                    var errors = [];
                    for (var key in resp.ModelState) {
                        for (var i = 0; i < resp.ModelState[key].length; i++) {
                            errors.push(resp.ModelState[key][i]);
                        }
                    }
                    $scope.errors = errors;

                });

        }
        else {
            toastr.warning('Invalid User Form, correct errors and try again.');
        }
    };

2 个答案:

答案 0 :(得分:18)

在拨打您的服务器时,请根据$http承诺的拒绝来捕获错误。

然后在你的控制器中,我会建议在处理显示错误时扁平化对一系列错误的响应,如fiddle example所示:

for (var key in resp.ModelState) {
    for (var i = 0; i < resp.ModelState[key].length; i++) {
        errors.push(resp.ModelState[key][i]);
    }
}

把它们放在一起:

// Post the data to the web api/service
$http.post(url, data)
    .success(successHandler)
    .error(function (response) {
        // when there's an error, parse the error
        // and set it to the scope (for binding)
        $scope.errors = parseErrors(response);
    });

//separate method for parsing errors into a single flat array
function parseErrors(response) {
    var errors = [];
    for (var key in response.ModelState) {
        for (var i = 0; i < response.ModelState[key].length; i++) {
            errors.push(response.ModelState[key][i]);
        }
    }
    return errors;
}

答案 1 :(得分:3)

最简单的方法可能是从ModelState中获取所有错误并将它们放入$ scope的新属性中。

$http.post(url, data).
    success(successHandler).
    error(function (response) {
        $scope.errors = getErrors(response);
    });

function getErrors(responseWithModelState) {
    var errors = [];
    /*
    Get error messages out of ModelState property, and push them into the errors variable...
    Brocco beat me to it. :-)
    */
    return errors;
};

然后在你的HTML中......

<ul>
    <li ng-repeat="e in errors">{{e}}</li>
</ul>

或者,不是在每个错误处理程序中执行此操作,而是可以编写一次,并通过使用拦截器将其应用于每个HTTP请求。我自己从未写过,所以我只是指向doc(向下滚动到拦截器部分)。