How set ID and use it dynamically in mvc 4 razor?

asp.net-mvc, attributes, click, javascript, jquery

Solution

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');
});

That way you're wired to all similar links (e.g. `select-list`) without a separate handler function for each #id.

Problem

I have html elements in `foreach`. I cannot declare ID name to those manually. I used `id='ProductSelect_@(item.Id)'` to set Id: ``` foreach (var item in Model) { <a href="#" id='ProductSelect_@(item.Id)' class="select-link">Select this</a> } ``` But, now I need .click() function for eash `<a>` link to do my some operations. How write click function for dynamic ID's? 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() functions send request to controller iteration counts times. What is wrong in my code?

Original source