Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2, jQuery POST data null

I use jQuery and send data with the POST method. But in the server method the values are not coming. What could be the error?

client

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "./AddTag",
    dataType: "json",
    data: "{'parentId':42,'tagName':'isTagName'}",
    success: function (response) {
        // ...
    }
});

server

[HttpPost]
public JObject AddTag(int parentId, string tagName)
{
    dynamic answer = new JObject();
    List<LogRecord> logs = new List<LogRecord>();
    answer.added = fStorage.Tags.AddTag(parentId, tagName, logs);
    return answer;
}

Brackpoint

Chrome

fixed Thank you all very much. I understood my mistake. I fixed the client and server code for this:

let tag = {
        "Id": 0,
        "ParentId": 42,
        "Name": isTagName
    };
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "./AddTag",
    dataType: "json",
    data: JSON.stringify(tag),
    success: function (response) {
        // ...
    }
});

server

    [HttpPost]
    public JObject AddTag([FromBody] Tag tag)
    {
        dynamic answer = new JObject();
        List<LogRecord> logs = new List<LogRecord>();

        answer.added = fStorage.Tags.AddTag(tag.ParentId, tag.Name, logs);
        answer.logs = Json(logs);

        return answer;
    }

The class has added

public class Tag
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
    public List<Tag> ChildsList { get; set; }
    [NonSerialized]
    public Tag ParrentTag; 
}
like image 841
al.koval Avatar asked Sep 08 '17 09:09

al.koval


1 Answers

Try extracting your params into a separate DTO class and do it like that:

public class ParentDTO 
{
 public int parentId{get; set;}
 public string tagName{ get; set;}
}

[HttpPost]
public JObject AddTag([FromBody] ParentDTO parent)
{

}
like image 172
Kostya Avatar answered Oct 16 '22 05:10

Kostya