ajax请求asp.net mvc从ajax请求向控制器传递ID值

问题描述 投票:0回答:1
  <h2>GetAllProducts</h2>

<table class="table">
<tr>

    <th>
        @Html.DisplayNameFor(model => model.Genre)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.AgeId)
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
    <tr>

        <td>
            @Html.DisplayFor(modelItem => item.Genre)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.AgeId)
        </td>

        <td> <button type="button" data-id="@item.Id" 
    class="productIdButton">AddProductToBasket</button></td>

    </tr>
}

@section scripts {

<script type="text/javascript">
    $("button").click(function () {
        //returns all the product ids
        //want to return the selected id of the button clicked
      //  var h = ($(this).data("id"));
        var h=  ($(this).attr("data-id"));

        var productId = (h.Id);
        var s = productId;
        //alert(productId);
        $.ajax({
            url: "/api/BasketAPI/AddProductToBasket/",
            type: "POST",
            data: { id: productId },
            contentType: false,
            cache: false,
            processData: false,
        });
    });


</script>

}

我正在尝试将在视图(JQuery)中找到的data-id =“ @ item.Id”值传递给控制器​​,并使用该值与类的ID进行比较。我不确定从ajax请求中获取id值。

 [Route("api/BasketAPI/AddProductToBasket/")]
    [HttpPost]
    public void AddProductToBasket(int id)
    {

        var returnAllProductIds = _productService.GetProductsById().Where(X=>X.Id==id).Select(x=>x.Id).FirstOrDefault();

目前,来自ajax请求的ID(该ID是分配给按钮的产品ID。每个按钮都具有分配给它的产品ID)没有传递给控制器​​。我希望将控制器中方法的参数中的id设置为来自ajax请求的id。目前尚未设置。

ajax asp.net-mvc asp.net-ajax
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.