How to bind html elements with dynamically created ID to jQuery events in asp.net MVC

465 Views Asked by At

I am iterating 3 times over a partial view in the Razor syntax. The code goes like this:

foreach(var item in Model.items) //Will be run 3 or more times
{
    {Html.RenderPartial("_viewname", item)}
}

Inside _viewname.cshtml, I am creating a table. Now I want to bind these tables to a jQuery Event, for which I am writing this:

$('#tbl tbody').on('click', 'tr', function () {
//Code goes here
});

Now the problem is that this event is getting called 3 times even when I click on any one of the table.

I want to somehow differentiate between the 3 tables. If I provide them different HTML ID's, then how should I write my jQuery code to capture it?

For example, _viewname.cshtml looks like this:

@model abc
<table id="tbl">
    //table body and other stuff
</table>

If I put id as "[email protected]", how to make sure that jQuery event is called.

P.S - There are other partial views within _viewname.cshtml, all of which should have uniquely identifiable ID.

1

There are 1 best solutions below

2
Kelvin Snepvangers On

You can get the element that triggered the event by addidng a parameter to the function like:

$('#tbl tbody').on('click', 'tr', function (event) {
    console.log(event.target.id);
});

And then getting the target of the event