0

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?

2 Answers 2

3

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

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

3 Comments

Thx for the reply, I'll try it. If I have an Index method in Home controller, should I write ajax function just like this? $.ajax({ url: '/Home/Index', type: 'POST', dataType: 'application/json; charset=utf-8', data: JSON.stringify(canvas), async: false });
you can check the api in jquery here api.jquery.com/jquery.ajax, and it should be contentType instead of dataType and charset. You could skip the JSON.stringify as well I guess
ep, this works. Thanks a lot for your answer instead of downvoting.
0

The original answer looks to use a dynamic object to handle the JSON string.

An alternative approach would be to capture the JSON string into a string.

public IActionResult xxx(string id, [FromBody] string jsonString)

And then de-serialize it.

MyData myData = new JavaScriptSerializer().Deserialize<MyData>(jsonString);

Comments

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.