2

How to Post data using Web API in Knockout JS.

When I post the data, it gives mn Bad Request Error. . .

I have the following 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 !!');
                }
            };

Update:

here is the controller action

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
  • How does your controller action look like? Commented Sep 5, 2013 at 18:45
  • 2
    Looks like your POST is reaching the controller but the model data is invalid. Try (a) viewing the actual HTTP request that your app is sending and (b) use something like Fiddler to test sending a POST request, and see if there is any difference. Commented Sep 5, 2013 at 19:38
  • Should you be referencing self.Student in this line "data: ko.toJSON(Student)"? When debugging in VS you can also check the ModelState to see specifically what errors it has. Debugging will also help you see if everything is mapping correctly to the Student object. Commented Sep 16, 2013 at 14:12
  • See if this helps though Angular - Using AngularJS to send parameters to Web API Commented Jul 31, 2014 at 4:00

1 Answer 1

1

You have some errors in your viewModel.

  1. In $.ajax you should convert json object to string, use JSON.stringify.
  2. Pass url via ViewBag it is very bad idea, declare it as static, or pass in ViewModel on creation.

So, your $.ajax should looks like this:

var submitData = ko.toJSON(Student);
$.ajax({
    url: baseUri,
    cache: false,
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(submitData),
    success: function (data) {
        // alert('added');
        self.Students.push(data);
        self.Name("");
        self.Age("");
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.