2

で Web API を使用してデータを投稿する方法Knockout JS

データを投稿すると、mn Bad Request Error が表示されます。. .

私は次のものを持っています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);
            }
        }
4

1 に答える 1