2

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!

dafna
  • 893
  • 2
  • 10
  • 21
  • Why not just use `public JsonResult Post(string data)`? Never use `JsonResult` as action method argument because it used to return JSON data. – Tetsuya Yamamoto Nov 21 '17 at 08:55

2 Answers2

4

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.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • That's now working with JSON. Thanks a lot! But you're right. To use my model (already existing) that would be better. Do you want to give me a hint how I have to do this? I created this method to get and set my MVC-modelconsisting of id and name: public class EmployeeViewModel { public IEnumerable Employees { get; set; } } – dafna Nov 21 '17 at 08:58
  • You just change the parameter type to `EmployeeViewModel`. – CodeCaster Nov 21 '17 at 09:03
1

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
    }