Mark Fenech
Mark Fenech

Reputation: 1358

MVC getting id on button click

I am trying to get the id of the selected button.

This is my code below

 <% foreach (var item in Model.getLeagues) { %>
        <a href=Teams.aspx class="leagueImage">
            <img src="../../<%: item.image %>" alt="<%: item.name %>" />
            </a>
    <% } %>

With this code I am generating 5 buttons and then I need the id of the clicked button.

Any help of how I can get this id ?

Thanks

Upvotes: 2

Views: 4499

Answers (3)

JasCav
JasCav

Reputation: 34652

If you want to get the ID from the controller, why not take the suggestion Marko made, but instead of putting it into the id attribute, instead put make it part of your href tag and pass the ID attribute.

By default, the routing in MVC expects back an ID which is part of your route in:

http://sitename/{Controller}/{Action}/{Id}

So, you could do something like this (I'm going to use Razor syntax, but, you can adjust):

@for(var i = 0; i < Model.getLeagues.Count; i++) {
  Html.ActionLink("Button Name", "Index", "MyController", new { id = Model.getLeages[i] }, new { @class="classname", alt = "@Model.getLeagues[i].name" }) %>
}

And, in your controller (rename as appropriate) you would have:

public class MyController : Controller {
  public ActionResult Index(int id) {
    // Do stuff with the ID that you get back here.
  }
}

Also, you'll notice that I broke out your image information. Instead, make a class in your stylesheet like:

a.classname
{
    background: url(../Images/image.gif) no-repeat top left;
    /* Do whatever else you need to do here to style your buttons. */
}

I didn't check any of the code, so can't guarantee it's syntactically perfect, but that should get you going down a right path.

I did notice your path to Teams.aspx. If you are coming from WebForms, you can edit your routing file to direct towards the RESTful route like this:

routes.MapPageRoute("Teams", "MyController/Index", "~/WebForms/Index/Teams.aspx");

(Credit to: https://stackoverflow.com/a/10175580/132528)

Upvotes: 3

Marko
Marko

Reputation: 13273

If you change your loop to following:

<% for (var i = 0; i <= Model.getLeagues.Count; i++) { %>
    <a href="Teams.aspx" id="link_<%: i %>" class="leagueImage">
        <img src="../../<%: Model.getLeagues[i].image %>" alt="<%: Model.getLeagues[i].name %>" />
        </a>
<% } %>

now you have anchor tags with unique IDs (link_0, link_1, ...). So now using jquery click event like this:

$(document).ready(function() {

   $(".leagueImage").click(function() {
      alert($(this).id);
   });

});

will get you a popup box that will display the ID of the clicked anchor tag.

Upvotes: 2

Paul
Paul

Reputation: 12440

If you are looking to get the index of the collection you are looping though, try this:

Model.getLeagues.indexOf(item)

Upvotes: 0

Related Questions