Richard77
Richard77

Reputation: 21611

How to add a id attribute to @Html.ActionLink?

@Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { data_id = "edit_" + item.Id })

I hope this is the right syntax. The idea is to intercept the click of one of those anchor link and be able to tell which one was clicked, then extract the id.

I have other anchor tags in the page. How do I select this particular one?

Upvotes: 0

Views: 5525

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

There are two ways.

  1. use Id attribute
  2. use html5 data attribute.

Razor

@Html.ActionLink("Edit", "Edit", 
                   new { id = item.Id }, 
                   new { data_id = item.Id, id = item.Id })

Jquery

$('a').click(function(){
    
    alert($(this).data("id")); // alerts data-id attribute    
    //or    
    alert(this.id); // this alerts Id attribute    
});

Upvotes: 0

Sam Axe
Sam Axe

Reputation: 33738

Using jQuery to select that element. This assumes that this is the only anchor tag that has a data-id with that value.

$('A[data-id="@item.Id"])')

If you have multiple anchor tags with identical data-id values then you can add an id attribute to the anchor, thusly:

@Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { data_id = "edit_" + item.Id, id = "some unique id" })

and select it using that id:

$('#some unique id')

Upvotes: 1

Related Questions