-1

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 "tbl_@Model.uniqueId", 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.

Anshul Dahiya
  • 640
  • 7
  • 11
  • 1
    ids should be unique in any case – Pete Jun 25 '18 at 12:13
  • Scripts do not go in partials (only the view or its layout). What makes you think you want them to have ID's? –  Jun 25 '18 at 12:14
  • Provide a [mcve] – Asons Jun 25 '18 at 12:16
  • @Pete Just added the code of viewname.cshtml and the description. Let me know if that makes sense to you – Anshul Dahiya Jun 25 '18 at 12:19
  • 1
    read my comment, I don't think I need to expand on it – Pete Jun 25 '18 at 12:20
  • Replace your `id` with a class name (duplicate `id` attributes are invalid html) and then `$(this)` gives you the ``, and `$(this).closest('table')` gives you the table (and put the script in the view, not in the partial) –  Jun 25 '18 at 12:39

1 Answers1

0

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