dafna
dafna

Reputation: 973

POST JSON from Angular frontend to ASP.NET backend

I would like to send data (originally arrays) as JSONs to my MVC-controller in the backend. I was trying this:

my-ng-service.ts

//...
setEmployees(employees) {
    var employeesJSON = JSON.stringify(employees);
    console.log(employeesJSON); //working
    this.http.post('/api/employees', employeesJSON).subscribe();
}
//...

EmployeesController.cs

//...
[Route("api/[controller]")]
[HttpPost]
public void Post(JsonResult data)
{
    Console.Write("hallo: " + data); //error see below
}
//...

I don't know how I have to write my controller. Can anybody help me?

Current error:

System.Argument.Exception: Type 'Microsoft-AspNetCore.Mvc:JsonResult' does not have a default constructor Parameter name: type

Thanks in forward!

Upvotes: 2

Views: 1922

Answers (2)

Ashiqur Rahman Emran
Ashiqur Rahman Emran

Reputation: 207

Actually write the model name that you want to get from http request

[Route("api/[controller]")]
    [HttpPost]
    public void Post(YourJsonModel ModelObject)
    {
        Console.Write("hallo: " + data); //error see below
    }

Upvotes: 1

CodeCaster
CodeCaster

Reputation: 151654

JsonResult is a type you use to output JSON from an action method, not as input parameter.

See ASP.NET Core MVC : How to get raw JSON bound to a string without a type? and ASP.NET MVC Read Raw JSON Post Data: you can change the parameter type to dynamic or JObject, or you can manually read the request body as string.

But you should really reconsider this. Creating a model so you can bind your model strongly-typed is a matter of seconds work, and will benefit you greatly in the future.

Upvotes: 4

Related Questions