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!

1
  • Why not just use public JsonResult Post(string data)? Never use JsonResult as action method argument because it used to return JSON data. Commented Nov 21, 2017 at 8:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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> Employees { get; set; } }
You just change the parameter type to EmployeeViewModel.
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
    }

2 Comments

But then you have to have a model.
Yeah If i dont have any model then jobject and dynamic is alright either we can grab the value from Request also

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.