带路由控制器的HttpPut

时间:2017-03-07 09:09:35

标签: javascript c# .net ajax asp.net-mvc

嗨我需要一些帮助我试图用ajax将一些数据发送到控制器使用PUT方法在这里做更新是javascript和ajax代码:

function UpdateProduct() {
var id = location.pathname.split('/')[2];

var product = {
    Name: $("#txtName").val(),
    Description: $("#txtDescription").val(),
    Price: $("#txtPrice").val(),
    SubCategoryId: $("#txtSubCategoryId").val(),
    CompanyId: $("#txtSubCategoryId").val(
    ProductCode: $("#ProductCode").val(
    Barcode: $("#Barcode").val(
    Brand: $("#txtBrand").val(),
    Material: $("#txtMaterial").val(),
    Date: $("#txtDate").val(),
};

$.ajax({
    url: "/UpdateProduct/"+id,
    type: "PUT",
    dataType: "json",
    data: product,
    success: function (result) {
        alert('Successful');
    },
    error: function (e) {
        alert(e.error);
    }
});

};

和我的控制器代码:

[HttpPut]
    [Route("UpdateProduct/{id}")]
    public void UpdateProduct(int id, ProductsBE product)
    {
        var api = ConfigurationManager.AppSettings["apiUrl"];
        var productsById = new ProductsRep();
        var searchResponse = productsById.UpdateProduct(product,id, api);
    }

API正在运行,因为我已经用邮差测试了它。

1 个答案:

答案 0 :(得分:0)

您必须使用JSON.stringify将对象product转换为json字符串

$.ajax({
    url: "/UpdateProduct/"+id,
    type: "PUT",
    dataType: "json",
    data: JSON.stringify(product),
    success: function (result) {
        alert('Successful');
    },
    error: function (e) {
        alert(e.error);
    }
});