ASP.NET Core 2, jQuery POST data null

2020-06-12 02:51发布

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

3条回答
放荡不羁爱自由
2楼-- · 2020-06-12 03:38

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)
{

}
查看更多
狗以群分
3楼-- · 2020-06-12 03:38

Change your ajax to this

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

});

查看更多
Luminary・发光体
4楼-- · 2020-06-12 03:50

Use [FromBody] before the param. It's check and Get the Property value in body otherwise it's check the Url Querystring.

Example:

[HttpPost]
public JObject AddTag([FromBody] int parentid,[FromBody]string tagname)
{

}

[HttpPost]
public JObject AddTag([FromBody] {ModelName} parent)
{

}
查看更多
登录 后发表回答