How to set id and use it dynamically in mvc 4 razor?

I have html elements in foreach . I cannot declare an ID name for this manually. I used id='ProductSelect_@(item.Id)' to set the Id:

  foreach (var item in Model) { <a href="#" id='ProductSelect_@(item.Id)' class="select-link">Select this</a> } 

But now I need the .click () function for the eash <a> link to perform some of my operations. How to write a click function for dynamic identifiers?
I checked this, but it does not work:

 $("#ProductSelect_@(item.Id)").click(function () { //any operation }); 

Edit:

 <script> $(document).ready(function () { $('.select-link').click(function() { var id = $(this).attr('data-id'); url = '@Url.Action("SelectThis", "Product")'; var data = { id: '@Model.Id' }; $.post(url, data, function (result) { if (result.success) { alert("Thanks"); } else { alert("Problem occured..."); } }); }); }); </script> 

This click () function sends a request for the duration of the iterations of the controller. What is wrong in my code?

+8
javascript jquery asp.net-mvc attributes click
source share
1 answer

I would suggest using attributes.

  foreach (var item in Model) { <a href="#" data-id='@item.Id' id='ProductSelect_@(item.Id)' class="select-link">Select this</a> } 

then in js ...

 $('.select-link').click(function() { var id = $(this).attr('data-id'); }); 

Thus, you are connected to all similar links (for example, select-list ) without a separate handler function for each #id.

+11
source share

All Articles