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;
}
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;
}
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)
{
}
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)
{
}
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) {
// ...
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.