我使用jQuery
并使用POST
方法发送数据。但在服务器方法中,值不会到来。什么可能是错误?ASP.NET Core 2,jQuery POST数据null
客户
$.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;
}
固定 非常感谢大家。我明白我的错误。我定了这个客户端和服务器代码:
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;
}
你发送JSON,而不是查询字符串,改变你的'data'是 “的parentId = 42&标签名= isTagName” 和'dataType'到'pplication/X WWW的形式 - urlencoded“并重试。 –
本示例在ASP.NET MVC中正确工作。由服务器处理POST方法有什么区别? –
“JSON”与两个“字符串”是不同的类型,所以值得一试。 –