Search code examples
jqueryajaxasp.net-mvcodata

How correct use Patch reqvest with odata


I have next method Odata method under asp mvc solution, this method 100% generated by wizard just for my learn case.

 [AcceptVerbs("PATCH", "MERGE")]
        public async Task<IHttpActionResult> Patch([FromODataUri] long key, Delta<SchoolChildrens> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            SchoolChildrens schoolChildrens = await db.SchoolChildrensSet.FindAsync(key);
            if (schoolChildrens == null)
            {
                return NotFound();
            }

            patch.Patch(schoolChildrens);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SchoolChildrensExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(schoolChildrens);
        }

I have next Javascript code for call this method:

 self.updateItem = function (data) {
     var student = ko.toJS(data);

     $.ajax({
         url: '/odata/SchoolChildrens(' + student.Id + ')',
         data: JSON.stringify(student),
         type: 'PATCH',
         success: function () {

         },
         error: function () {

         },
         xhr: function () {
             return window.XMLHttpRequest == null || new window.XMLHttpRequest().addEventListener == null ? new window.ActiveXObject("Microsoft.XMLHTTP") : $.ajaxSettings.xhr();
         }
     });
 };

My record never updated via this method. how to use it correctly ? How I should send Delta ?


Solution

  • Does it work to add:

    $.ajax({
    ...
    contentType: 'application/json; charset=utf-8',
    datatype: 'json',
    ...
    };