简体   繁体   中英

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...

在此处输入图片说明

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();
}

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

I know that is already marked as answered, but here is another way to do it:

I am not using the binding FromBody attribute.

Controller

    public class JsonRequest
    {
        public string Id { get; set; }
    }

    [HttpPost]
    public ActionResult Save(JsonRequest data)
    {

        return Json(data.Id);
    }

Instead of using dataType I am using accept and you don't need to convert your json into a string.

To avoid problems with relative paths I am using: url: '@Url.Action("Save", "Home")' as well.

Javascript

function send()
{
    //JSON data
    var dataType = 'application/json';
    var data = {
        "id": "Zaki"
    }

    console.log('Submitting form...');
    console.log(data);
    $.ajax({
        type: 'POST',
        url: '@Url.Action("Save", "Home")',                        
        accept: dataType,
        data: data,
        success: function (result) {
            console.log('Data received: ');
            console.log(result);
        }
    });
}

Good luck with your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM