awj
awj

Reputation: 7959

jQuery PATCH request not recognised by Marvin.JsonPatch

I'm trying to send an AJAX PATCH request to a Web API method and have the patched object recognised by Marvin.JsonPatch.

So far, everything I've sent to the server has resulted in an empty request being received.

The Web API controller method looks like this:

public IHttpActionResult Update(ElementType elementType,
                                long elementId,
                                [FromBody] JsonPatchDocument<TranslationMatchDiscounts> matchDiscountsPatch)

And that TranslationMatchDiscounts object is very straightforward:

public class TranslationMatchDiscounts
{
    public double ContextMatches { get; set; }


    public long ElementId { get; set; }


    public Enumerations.ElementType ElementType { get; set; }


    public double ExactMatches { get; set; }


    public double PerfectMatches { get; set; }


    public double Repetitions { get; set; }
}

And my jQuery AJAX request is put together like this:

$.ajax({
    //contentType: "application/json",
    data: { "Repetitions": 0.15 },
    //data: JSON.stringify({ "Repetitions": 0.15 }),
    dataType: "json",
    //processData: false,
    method: "PATCH",
    url: // my URL
});

The commented-out properties show some things I've tried.

The controller does get hit, that's not the problem, and the "Repetitions" property is being sent but the server-side JsonPatchDocument<TranslationMatchDiscounts> parameter is either...

What is the correct way to send a PATCH request using jQuery's .ajax()?

Upvotes: 0

Views: 1457

Answers (1)

awj
awj

Reputation: 7959

My fault. I was under the impression that PATCH allowed us to post an object with only the changed properties, i.e....

{
    "Repetitions": 0.15
}

No. What PATCH requires is a JSON patch document. According to the RTF:

A JSON Patch document is a JSON [RFC4627] document that represents an array of objects.

So my example should really be

var patchDoc = [ { "op": "replace", "path": "/Repetitions", "value": 0.15 } ];

$.ajax({
    contentType: "application/json",
    data: JSON.stringify(patchDoc),
    dataType: "json",
    method: "PATCH",
    url: // my URL
});

Upvotes: 2

Related Questions