I have a controller action in ASP.Net Core that is returning a BadRequest
with some model state. I want to flatten the validation messages into a single array within my Angular promise error handler. I'm not sure how to go about doing it though.
This is how I am returning the BadRequest
in my Web API controller action.
return base.BadRequest(base.ModelState);
Then in my Angular controller, I have an error handler like this for now.
(function () {
angular.module('app')
.controller('AccountCreationController', AccountCreationController);
function AccountCreationController(AccountCreationService) {
var viewModel = this;
viewModel.accountSetup = AccountCreationService.getAccountTypes();
viewModel.create = create;
viewModel.errors = new Array();
function create(user) {
var result = AccountCreationService.createAccount(user).$promise.then(function (response) {
var x = response;
},
function (error) {
// iterate over each key in the key/value pair.
for (var key in error.data) {
// iterate over each element in the data[key] array of validation messages
for (var e in error.data[key]) {
errors.push(e);
}
}
});
}
}
})();
The error
object has a data
property on it, that contains the model state array. The model looks like this:
I can get access to the array of validation messages by typing error.data["1"]
into the Chrome console, and I can get the message shown in the screenshot with error.data["1"][0]
. However, when I try to iterate over the data property to pull out the errors into a flattened array, the array is empty. I'm not sure what I'm doing wrong here (new to JS) - I was iterating over each key in the data
property, then iterating over each value in the array held for that key.
What am I supposed to do in order to get the underlying array of messages out?
edit
If I run the for loop in the Chrome console, I get the following output
var errors = new Array();
for (var key in error.data) {
for (var e in error.data[key]) {
console.log(key + ":" + e[0]);
}
}
1:0