Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 948
Jeyhun Rahimov Avatar asked Jan 18 '13 19:01

Jeyhun Rahimov


1 Answers

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.

like image 162
Eli Gassert Avatar answered Oct 10 '22 15:10

Eli Gassert