skip to Main Content

I use this foreach:

foreach (var item2 in RItem.GetChildItems(item.ID_Ca))
{
    <div id="@idc" class="accordion-collapse collapse" aria-labelledby="headingTwo2" 
         data-bs-parent="#accordionExample">
        <div class="accordion-body" style="background: white; padding: 5px; padding-left: 20px;">
            <button id="getthis" data-id="@item2.Name_Ca"  type="button" onclick="Search()" 
                    style=" color: #0028ff; font-size: 14px;">
                @item2.Name_Ca
            </button>
        </div>
    </div>
}

When the button is clicked, I want to send the data-id of the button to the controller through jQuery, the problem is that every time I click on the button, the only data that is sent to the controller is only the first record.

<script>
    function Search() {
        jQuery('.loading').fadeIn();

        $.ajax({
            url: 'SearchProjectsItems',
            type: 'post',
            datatype: 'json',
            data: {
                Cat: $(document.getElementById('getthis')).attr('data-id')     
            },
            error: function (err) {
                alert(err.Status + "" + err.StatusText);
            }
        }).done(function (data) {
            $('#Search_CU').html(data);
            jQuery('.loading').fadeOut();
        });
    }
</script>

I don’t know what to do

2

Answers


  1. change your html code button to onclick="Search(‘@item2.Name_Ca’)" . other wise use angular js. $scope.arrayname[] and fill the array and then send the data. Another method is use $scope.modelList and fill the list using angular foreach. then send to controller. controller function input parameter should be same data model.

    Login or Signup to reply.
  2. Use this identifier. this keyword refers to the current execution of code.

    in razor code pass this prameter,

    onclick="Search(this)"
    

    in JQuery Search function receive clicked button element.

    <script>
        function Search(btnElement) {
            ...
                data: {
                    Cat: $(btnElement).attr('data-id')     
                }
            ...
        }
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search