ASP.NET Core 2,jQuery POST数据为null

al.*_*val 10 c# ajax jquery post asp.net-core

我使用jQueryPOST方法并使用该方法发送数据.但在服务器方法中,值不会到来.可能是什么错误?

客户

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

服务器

[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;
}
Run Code Online (Sandbox Code Playgroud)

Brackpoint

铬

固定 非常感谢大家.我理解我的错误.我为此修复了客户端和服务器代码:

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) {
        // ...
    }
});
Run Code Online (Sandbox Code Playgroud)

服务器

    [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;
    }
Run Code Online (Sandbox Code Playgroud)

该课程已添加

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; 
}
Run Code Online (Sandbox Code Playgroud)

Kos*_*tya 12

尝试将你的参数提取到一个单独的DTO类中,然后执行以下操作:

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

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

}
Run Code Online (Sandbox Code Playgroud)


小智 5

[FromBody]在参数之前使用 。检查并获取主体中的Property值,否则检查Url Querystring。

例:

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

}

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

}
Run Code Online (Sandbox Code Playgroud)