ASP.NET Core 2,jQuery POST数据null

时间:2017-09-08 09:50:17

标签: c# jquery ajax post asp.net-core

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

客户端

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

服务器

[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

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

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) {
        // ...
    }
});

服务器

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

该课程已添加

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 个答案:

答案 0 :(得分:11)

尝试将你的参数提取到一个单独的DTO类中并按照这样做:

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

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

}

答案 1 :(得分:5)

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

示例:

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

}

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

}

答案 2 :(得分:-4)

将您的ajax更改为此

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

});