Search code examples
jsonasp.net-corecontrollertransfer

Sending JSON string to ASP.NET Core MVC Controller


I know how to send simple objects from JavaScript to an ASP.NET Core Controller. But what I'm suppose to do when I have complex a JSON string?

For example I'm using Factory lib. in JavaScript, so when I'm serializing my current Canvas data I'm getting JSON string like this: enter image description here

The question is : should I create this complex model in my ASP.NET Core app or is there any other way to get this JSON string in my Controller?

Can I consume a simple json string in my Controller?


Solution

  • It's up to your needs actually.

    If you do need a model which provides some methods to process the data, then creating a model could be a good idea.

    If you just need to deserialize the JSON string and extract values, you could write your controller like

    public ActionResult xxx ([FromBody]dynamic postData)
    

    It will receive the request body as string now.

    Be sure to set content-type as application/json in your javascript code

    enter image description here