When using contentType: 'application / json; charset = utf-8 ', then my data is not passed to the api controller

I, m, update the record using PUT in the web api when I use contentType: 'application / json; charset = utf-8 ', then my data is not transmitted to the api controller, but when I comment on the data of this line, it is transmitted. can anyone explain this? below is my call from mvc view

$(function () {
        $("#btnSubmit").click(function () {
            var id = $("#hdnProductID").val();
            var ProductName = $("#txtProductName").val();
            var QuantityPerUnit = $("#txtQuantityPerUnit").val();
            var ReorderLevel = $("#txtReorderLevel").val();
            var UnitPrice = $("#txtUnitPrice").val();
            var UnitsInStock = $("#txtUnitsInStock").val();
            var UnitsOnOrder = $("#txtUnitsOnOrder").val();

            $.ajax({
                url: "http://localhost:2821/api/Products"+ "/" + id,
                type: 'PUT',
                contentType: 'application/json; charset=utf-8',
                data:{ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder},
                success: function (data) {
                    alert("success");
                },
                error: function (msg) {
                    alert(msg);
                }

            });
        });
    });

Below is my management method

public IHttpActionResult PutProduct(int id, Product product)
 {}
+4
source share
1 answer

contentType , contentType, "application/x-www-form-urlencoded; charset = UTF-8", post, contentType "" /json; charset = utf-8 ", postfy. :

    $.ajax({
            url: "http://localhost:2821/api/Products"+ "/" + id,
            type: 'PUT',
            contentType: 'application/json; charset=utf-8',
            data:JSON.stringify({ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder}),
            success: function (data) {
                alert("success");
            },
            error: function (msg) {
                alert(msg);
            }

        });
+1

Source: https://habr.com/ru/post/1614550/


All Articles