1

Using Angular 6 & C# here.

On the button click event of my form I want to save the data. The event calls an API which saves the data.

Below is my button click event:

submitData() {

      //After getting form values I create an object as below
      let myData = 
      {
        "name":name,
        "date": date,
        "status": status,
        "selection":selection,
        "createdBy": createdBy
      };

   this.myService.save(myData)
    .subscribe(
     (jsonData) => {
        //redirect etc after save

     });  
 }

In my above event selection itself holds array of objects as:

  0: {name: "u1", id: "123", type:"dev", comment: "comment1"}
  1: {name: "u2", id: "456", type:"prd", comment: "comment2"}

Also below is my service call:

   saveExtract(data) {
    return this.httpClient.post<any>(this.url + '/Save', data)
  .pipe(
    catchError())
);

}

Finally below is my c# api;

 [HttpPost("Save", Name = "Save")]
    public async Task Save([FromBody] SaveModel data)
    {
       //do save here etc
    }

But above code returns me 400 (Bad Request) error.

I even try to put the breakpoint in my api but its never hit.

So looks like something is wrong while I call my post.

Can Anyone point out the issue?

Thanks

---Updated---

So I was missed out the code to pass httpOptions and using Json.stringify. After passing it partially works as below:

const httpOptions = {
      headers: new HttpHeaders({
      'Content-Type': 'application/json'       
      })
    };

 saveExtract(data) {
    return this.httpClient.post<any>(this.url + '/Save', data, httpOptions)
  .pipe(
    catchError())
);

 this.myService.save(JSON.stringify(myData))
.subscribe(
 (jsonData) => {
    //redirect etc after save

 });

The above code works when I comment out the selection array which is a part of my data to be passed to the API. But does not work and gives bad request error when I pass selection array.

So can anyone point how can I pass array of object to it.

3
  • Do you have any server side model validation on SaveModel? Do you have any server side Action Filters on your Save action or global Action Filters? Commented Apr 17, 2019 at 17:21
  • @Igor I have updated my post above, please have a look Commented Apr 17, 2019 at 17:39
  • What is the defination for SaveModel? Share us the full controller code. Commented Apr 18, 2019 at 6:50

1 Answer 1

2

Here is a working demo with sending array to .net core, check the differences from your code.

Client Angular

export class FetchDataComponent {
constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {

    let selection = [{ "name": "n1", "id": 1 }, { "name": "n2", "id": 2 }, { "name": "n3", "id": 3 }];
    let myData =
    {
    "name": "Tom",
    "selection": selection,
    };
    http.post<any>(baseUrl + 'api/SampleData/Save', myData).subscribe(result => {

    });
}
}

Serser side.

[Route("api/[controller]")]
public class SampleDataController : Controller
{       
    [HttpPost("Save", Name = "Save")]
    public async Task Save([FromBody] SaveModel data)
    {
        //do save here etc
    }       
}

public class SaveModel
{
    public string Name { get; set; }
    public List<MySelection> Selection { get; set; }
}
public class MySelection
{
    public int Id { get; set; }
    public string Name { get; set; }
}

One More Node, you could add code below in Startup.cs to avoid api model validation filter.

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });
Sign up to request clarification or add additional context in comments.

2 Comments

I have similar code but its just that my model Selection property is defined as: public List<string> Selection { get; set; } = new List<string>(); Is this not correct?
API was expecting array of strings and I was sending an array of objects. Thanks for pointing out that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.