$.ajax patch method and .net 8 api action

S R, Senthil 20 Reputation points
2024-05-21T05:35:16.4333333+00:00

Error Response Test -

"{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"$":["The JSON value could not be converted to Microsoft.AspNetCore.JsonPatch.JsonPatchDocument`1[HttpPatchApi.Models.ProductModel]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."],"productDoc":["The productDoc field is required."]},"traceId":"00-4d8533ec8e406ab17aa1ca6e2ac847e6-627f8f472a9de603-00"}"

.Net 8, Wep Api Action -

[HttpPatch]

public ActionResult UpdateOffer(int id, [FromBody] JsonPatchDocument<ProductModel> productDoc)

{

ProductModel product = ProductModelFaker.GetProductModel(id);

productDoc.ApplyTo(product);

return Ok(ProductModelFaker.UpdateProductModel(product));

}

jQuery Ajax Patch Call -

function saveOffer() {

var apiUrl = _baseApiUrl + "UpdateOffer/?id=" + $("#txtID").val();

var prodcutDoc = [

    { "op": "replace", "path": "/OfferDescription", "value": $("#txtOfferDescription").val() },

    { "op": "replace", "path": "/OffferPercentage", "value": $("#txtOffferPercentage").val() }

];

$.ajax({

    url: apiUrl,

    type: 'PATCH',

    data: JSON.stringify(prodcutDoc),

    contentType: 'application/json-patch+json',

    accepts: 'application/json',

    success: function (response) {

        loadProductToUi(response);

    },

    error: function (error) {

        console.log("Error in saveOffer:");

        console.log(error);

        alert("Error in saveOffer:" + error.responseText);

    }

});

return true;

}

Payload -

User's image

Clarification -

What is the misting? What is the fix?

Thanks in advance.

Senthil S R

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,904 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,594 questions
JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
994 questions
{count} votes

Accepted answer
  1. Tiny Wang-MSFT 2,731 Reputation points Microsoft Vendor
    2024-05-21T08:47:38.0466667+00:00

    Hi, I had a test in my side with your code snippet which worked well, I didn't reproduce your issue. I created a new .net 8 MVC application, and in the Index.cshtml, I have codes like below

    <button onclick="saveOffer()">send request</button>
    @section Scripts{
        <script>
            function saveOffer() {
                alert(1);
                var apiUrl = "https://localhost:7051/api/test?id=1";
                var prodcutDoc = [
                    { "op": "replace", "path": "/OfferDescription", "value": "changedDesc" },
                    { "op": "replace", "path": "/OffferPercentage", "value": "changedPer" }
                ];
                $.ajax({
                    url: apiUrl,
                    type: 'PATCH',
                    data: JSON.stringify(prodcutDoc),
                    contentType: 'application/json-patch+json',
                    accepts: 'application/json',
                    success: function (response) {
                        loadProductToUi(response);
                    },
                    error: function (error) {
                        console.log("Error in saveOffer:");
                        console.log(error);
                        alert("Error in saveOffer:" + error.responseText);
                    }
                });
                return true;
            }
        </script>
    }
    

    Then I followed this document to complete Patch request configuration, including adding .AddNewtonsoftJson(). Then please see my screenshot below, I create a simple ProductModel which worked well.

    User's image

    ======================================

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Tiny

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. S R, Senthil 20 Reputation points
    2024-05-21T20:04:12.09+00:00

    builder.Services.AddControllers().AddNewtonsoftJson(); - This will resolve ths issue. Thanks @Tiny Wang-MSFT .

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.