如何使用 Web API 在Knockout JS
.
当我发布数据时,它给出了 mn 错误请求错误。. .
我有以下ViewModel
function StudentViewModel() {
var self = this;
self.StudentID = ko.observable("");
self.Name = ko.observable("");
self.Age = ko.observable("");
var Student = {
StudentID: self.StudentID,
Name: self.Name,
Age: self.Age
};
self.Student = ko.observable();
self.Students = ko.observableArray();
var baseUri = '@ViewBag.ApiUrl';
$.getJSON(baseUri, self.Students);
self.create = function () {
if (Student.Name() != "" && Student.Age() != "") {
$.ajax({
url: baseUri,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Student),
success: function (data) {
// alert('added');
self.Students.push(data);
self.Name("");
self.Age("");
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
else {
alert('Please Enter All the Values !!');
}
};
更新:
这是控制器动作
public HttpResponseMessage PostStudent(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, student);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = student.StudentID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}