ajax 放置请求后,服务器上的接收对象属性为空
Receiving object properties are null on server after an ajax put request
我在通过向服务器发送 ajax
请求(方法是 PUT
)将数据从浏览器发送到服务器上的 API
时遇到问题。这是我的 JavaScript
代码:
var json = JSON.stringify({
StemType: {
ID: parseInt(this.dataset.id),
Type: this.dataset.type,
GebruikerID: "@(Model.DeTopic.Gebruiker.Id)"
},
Punten: parseInt(this.dataset.punten),
GestemdeGebruikerID: "@(Model.AangemeldeGebruiker)"
});
$.ajax({
url: "../Stem/Toevoegen",
type: "PUT",
data: json,
success: function (returnData) {
// my code
}
});
这是变量json中的代码json:
{
"StemType": {
"ID": 24731,
"Type": "Topic",
"GebruikerID": "539e6078"
},
"Punten": 1,
"GestemdeGebruikerID": "3aedefab"
}
这是服务器上的 C# 代码。
public class StemController : ApiController
{
[HttpPost]
[Authorize]
[Route("Stem/Toevoegen")]
public void Toevoegen([FromBody]Stem stem)
{
Console.WriteLine(stem.ToString());
}
}
这里是 class Stem
:
public class Stem
{
public StemType StemType { get; set; }
public int Punten { get; set; }
public string GestemdeGebruikerID { get; set; }
}
public class StemType
{
public int ID { get; set; }
public Type Type { get; set; }
public string GebruikerID { get; set; }
}
但是如果我在服务器上调试我的代码,我得到了这个:
谁能帮帮我?
我找到了两种可能的方法:
- 不要将其字符串化以作为对象发送。
- 为 Json 代码添加
contentType: "application/json"
。
我在通过向服务器发送 ajax
请求(方法是 PUT
)将数据从浏览器发送到服务器上的 API
时遇到问题。这是我的 JavaScript
代码:
var json = JSON.stringify({
StemType: {
ID: parseInt(this.dataset.id),
Type: this.dataset.type,
GebruikerID: "@(Model.DeTopic.Gebruiker.Id)"
},
Punten: parseInt(this.dataset.punten),
GestemdeGebruikerID: "@(Model.AangemeldeGebruiker)"
});
$.ajax({
url: "../Stem/Toevoegen",
type: "PUT",
data: json,
success: function (returnData) {
// my code
}
});
这是变量json中的代码json:
{
"StemType": {
"ID": 24731,
"Type": "Topic",
"GebruikerID": "539e6078"
},
"Punten": 1,
"GestemdeGebruikerID": "3aedefab"
}
这是服务器上的 C# 代码。
public class StemController : ApiController
{
[HttpPost]
[Authorize]
[Route("Stem/Toevoegen")]
public void Toevoegen([FromBody]Stem stem)
{
Console.WriteLine(stem.ToString());
}
}
这里是 class Stem
:
public class Stem
{
public StemType StemType { get; set; }
public int Punten { get; set; }
public string GestemdeGebruikerID { get; set; }
}
public class StemType
{
public int ID { get; set; }
public Type Type { get; set; }
public string GebruikerID { get; set; }
}
但是如果我在服务器上调试我的代码,我得到了这个:
谁能帮帮我?
我找到了两种可能的方法:
- 不要将其字符串化以作为对象发送。
- 为 Json 代码添加
contentType: "application/json"
。