Search code examples
c#jsonasp.net-mvcentity-frameworkodata

Asp Mvc 5 Post to Odata never init data


I have created from wizard Asp Mvc 5 solution with Odata service to EF 6. I want to send post request and create a record in database but odata controller ran request, but not map JSON to EF object what is wrong with my ajax request ?

Odata Method:

   // POST: odata/SchoolChildrens
        public async Task<IHttpActionResult> Post(SchoolChildrens schoolChildrens)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.SchoolChildrensSet.Add(schoolChildrens);
            await db.SaveChangesAsync();

            return Created(schoolChildrens);
        }

JavaScript object Side (not all DB property here no need on client side):

  var children = function () {
            var self = this;        
            self.Id = ko.observable(0);
            self.FullName = ko.observable();
            self.IsPrivilege = ko.observable(false);
            self.UseInShortMenu = ko.observable(false);
        }

part of code that sent request, both case can't init data

 self.addItem = function () {
        var newStudent = ko.toJSON(self.newRow());
        $.post("/odata/SchoolChildrens", JSON.stringify(newStudent), function (result) {
            self.childrenList.push(result.value);
        }).fail(function () { console.log("Function : Add SchoolChildrens error"); });

        $.ajax({
            type: "POST",
            url: "/odata/SchoolChildrens",
            data: newStudent,
            success: function(result) {
                self.childrenList.push(result.value);
            },
            dataType: 'json',
            contentType: 'application/json'
        });


    };

I tried send JSON {schoolChildrens : ko.toJSON(self.newRow())} for map variable name but it also failed. How I should send post request to odata controller correctly ?


Solution

  • Firstly, check if your request really contains any data (request object from page contains not null or undefined data property)

    Second, when you use http methods that can send data in request body (POST, PUT, DELETE), it is necessary to add [FromBody] attribute before object as you want to map as method argument