ajax-запрос asp.net mvc передает значение id из ajax-запроса в контроллер - PullRequest
0 голосов
/ 18 октября 2019
  <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>

}

Я пытаюсь передать значение data-id = "@ item.Id", найденное в представлении (JQuery), на контроллер ииспользуйте это значение для сравнения с идентификатором класса. Я не уверен, что получаю значение id из запроса ajax.

 [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 из запроса ajax. На данный момент это не устанавливается.

1 Ответ

0 голосов
/ 19 октября 2019

Пожалуйста, попробуйте это.

CSHTML Страницы

<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" onclick="AddProductToBasket(@item.Id)" data-id="@item.Id" 
    class="productIdButton">AddProductToBasket</button></td>

    </tr>
}

Код JavaScript

@section scripts {

<script type="text/javascript">

    function AddProductToBasket(productid)
    {
        try
        {
            $.ajax({
            url: "/api/BasketAPI/AddProductToBasket",
            type: "POST",
            data: { id: productid },
            success: function(oData){
                alert(oData);
            },
            error:function(error)
            {
                alert(error);
            }
            });
        }
        catch(e)
        {
            alert(e.message);           
        }       
    }
</script>
}

Действие контроллера

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

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