0

I am transacting .NET API through Angular2(honestly.. 5) I implement server side-model validation using Data Annotations Attributes. As such, the API returns bad request(404) with the validation messages attached:

if (!ModelState.IsValid)
                return this.BadRequest(ModelState); 

My issue has to do on how to display those messages in my angular view.

My Angular service:

  submitForm(formObj: FormDto) {
    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json; charset=utf-8');

    return this.http.post("/api/Forms", JSON.stringify(formObj), { headers })
          .map((res: Response) => console.log(res));
         //need a .catch here obviously ??????
      }

and the way I call the service from the component itself:

  submitForm() {
    this.formService.submitForm(this.formObj)
      .subscribe(res => { console.log(res);

          //update this bit to display error messages ?????
                      });
   }

Again, my issue is how to display properly the returned validation error messages coming from the .NET API.

  • instead of returning BadRequest you can create a property on the model to store the error messages, other wise you have to iterate the `Modelstate` to get all the errors . . You can return 200 ok with the error messages property set if there are any errors. Then you can parse them in client side. – Niladri May 23 '18 at 12:40
  • There is an answer in SO to create an extension method for Modelstate that returns all the errors as a List<> . Check this https://stackoverflow.com/questions/1352948/how-to-get-all-errors-from-asp-net-mvc-modelstate – Niladri May 23 '18 at 12:41
  • @Niladri your solutions are working pretty good too – Georgios May 23 '18 at 14:02

1 Answers1

0

Let's star with the fact that the modelState is coming as an object(key-value pairs). Thus, you can access the object in view by a specific key. You can have a variable in your component and store the modelState object in it.

To the point....

I wouldn't touch the Angular service at all, but the way you subscribe to it in order to separate success and failed callback:

 submitForm() {
    this.formService.submitForm(this.formObj)
            .subscribe((data) => //do what ever on success,
                        (err) => { this.errors= err.error; });
   }

After that, you are able to see your error messages in the view. Something like:

<span class="error-message">{{errors['EmailAddress']}}</span>

Put the line above to every input it's needed but change the key to view the right message. I've done a quick demo and is working.

I hope that helped.

Georgios
  • 1,454
  • 6
  • 17
  • 34