c# – Unable to fetch/bind correct Entity Id in JQuery, always takes first item Id from iteration-ThrowExceptions

Exception or error:

I have a PartialView where I iterate over a Collection of Entities and display them in a Html Table.
One of the colomns of this table has a with a font awesome class (fa fa-times-circle).
I am setting the “id” property of this to the “Id” of my object I am iterating. I am setting a HiddenFor helper to get the Id in JQuery but I always get the top item from the HTML table.

When I look at the HTML output all Id’s seems fine however when I try to fetch this in JQuery like this:

<script type="text/javascript">
        $(function () {
        $("body").delegate(".fa", "click", function () {

            //Content to send
            var subscriptionId = $('#Subscription_SubscriptionId').val();

            $.get('@Url.Action("Action", "Controller")', { "subscriptionId": subscriptionId},
                function (result) { $('#SubscriptionBody').html(result); }
                );
         });
         });
</script>

I always have the Top item of the table.

This is how I iterate in my partial view:

foreach (var subscription in Model.Subscriptions)
{
    // tried both HiddenFor & Hidden but same results ... (HiddenFor should be used in my opinion)
    // when iterating all Id's are "good" (Different as they should be)
    @Html.HiddenFor(Model => Model.Subscription.SubscriptionId, new { Value = subscription.SubscriptionId })
    // @Html.Hidden("SubscriptionId", new { Value = subscription.SubscriptionId })

    <tr>           
        <td>@subscription.SubscriptionId</td>            
        <td>... some other values ...</td>  
         @if (condition)
         {
            <td>                    
                <i class="fa fa-user-plus fa-2x" id="@subscription.SubscriptionId"></i>
            </td>
         }
         else
         {
            <td>                   
                <i class="fa fa-times-circle fa-2x" id="@subscription.SubscriptionId"></i>
            </td>
         }
    </tr>
}

What am I doing wrong? Obviously I want to retrieve the “subscription.SubscriptionId” of the one I clicked in the table but somehow it always takes the top one.

Thank you for any suggestions or answers!

How to solve:

It seems to me that you might get like this

var subscriptionId = $(this).attr('id');

Explain:

  1. $('#Subscription_SubscriptionId').val() means: You are getting value from Subscription_SubscriptionId element instead of value of fa fa-times-circle.
  2. You can read this post of @Owais Alam’s answer to know the difference between attr and data in jquery.

Or you can refactor your code like this way

HTML:

<i class="fa fa-times-circle fa-2x" data-id="@subscription.SubscriptionId">

Jquery

var subscriptionId = $(this).data('id');

Leave a Reply

Your email address will not be published. Required fields are marked *