Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve JSON data in controller in ASP.net Core?

i need to get data sent with JSON and save to model in asp.net controller

  //JSON data
        var dataType = 'application/json';
        var data = {
            ID: 'Zaki',                
        }

        console.log('Submitting form...');
        console.log(data);
        $.ajax({
            type: 'POST',
            url: 'Save',
            dataType: 'json',
            contentType: dataType,
            data: data,
            success: function (result) {
                console.log('Data received: ');
                console.log(result);
            }
        });
          

Controller

 [HttpPost]
    public ActionResult Save([FromBody] string ID)
    {
       
        return Json (ID);


    }






          

am getting null in console , it supposed to be zaki and from there i wanna write saving code...

enter image description here

like image 392
Zakarie Abdallah Avatar asked Jan 31 '26 13:01

Zakarie Abdallah


2 Answers

Another way to do it is to simply use 'dynamic' type to handle json request data. Take a look:

[HttpPost]
public IActionResult YoutMethod([FromBody] dynamic requestData)
{
  Log.Information(requestData.field1);
  Log.Information(requestData.field2);
  // ...

  return Ok();
}
like image 129
rom5jp Avatar answered Feb 03 '26 08:02

rom5jp


Modify this line in your code data: data, to

data:JSON.stringify(data)

When sending data to a web server, the data has to be a string and JSON.stringify method converts a JavaScript object into a string.

Another approach would be, instead of getting raw string value, wrap your parameter into a class object like this

public class ParamObj
{
public string ID{get;set;}
}

and in your controller get a parameter of this object type like this..

public ActionResult Save([FromBody] ParamObj data)

Thanx

like image 41
Obaid Avatar answered Feb 03 '26 09:02

Obaid