我正在努力解决问题,我无法找到解决问题的方法。
这是我的班级学生:
public class Student
{
public int ID { get; set; }
public string Nume { get; set; }
public string Prenume { get; set; }
public int Nota { get; set; }
public bool Status { get; set; }
}
这是来自控制器的post方法:
[HttpPost]
public IHttpActionResult Post([FromBody] Student student)
{
if (student == null) return BadRequest();
studenti.Add(student);
return CreatedAtRoute("StudentApi", new { ID = student.ID }, student);
}
我尝试过发送JSON,如:
{ "ID": 6, "Nume": "Test", "Prenume": "TestP", "Nota": 10, "Status": true }
并返回它......每当我得到null并且没有元素被添加到列表中时......
答案 0 :(得分:0)
很难说出问题是什么,因为你没有向我们展示你如何调用Post动作,但是让我们说你有一个名为StudentController
的web api控制器看起来像这样:
public class StudentController : ApiController
{
[HttpPost]
public IHttpActionResult Post([FromBody] Student student)
{
if (student == null) return BadRequest();
//studenti.Add(student);
return CreatedAtRoute("StudentApi", new { ID = student.ID }, student);
}
}
要使用jQuery将Student
发布到Post动作,您可以执行以下操作:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAddStudent").click(function () {
var student = {
"ID": 6,
"Nume": "Test",
"Prenume": "TestP",
"Nota": 10,
"Status": true
}
$.ajax({
type: "POST",
url: "/api/Student",
data: student,
success: function (data) {
alert("New student created.");
},
error: function (error) {
alert("Called failed");
}
});
});
});
</script>
<input type="button" id="btnAddStudent" value="Add Student" />