Rahul Aggarwal
Rahul Aggarwal

Reputation: 291

Get Id of the row clicked from the table in MVC

I want to get Id of row clicked when a user clicks a button.

My code is as below.

   <table cellpadding="0" cellspacing="0" id="ProductGrid">
    <tr>
        <th>P Id</th>
        <th>P Name</th>
        <th>Price</th>
        <th></th>
    </tr>
    @foreach(Mvc4API.linqtosql.tblProduct prod in Model)
    {
        <tr>
            <td>@prod.Pid</td>
            <td>@prod.Pname</td>
            <td>@prod.Price</td>
            <td><button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview()"></button></td>
        </tr>
    }
</table>

I tried:-

function getview() {
    debugger;
    var productId = $("#ProductGrid .ids").closest("tr").find("td").eq(0).html();
});

But it is not working.

Upvotes: 3

Views: 9053

Answers (4)

althaf a s
althaf a s

Reputation: 71

Just update the tag.

button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview()"

to

button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview(this)"

It will give you the id in script.

Upvotes: 2

Alsamil Mehboob
Alsamil Mehboob

Reputation: 404

Try following code.

View

<td><button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview(@prod.Pid)"></button></td>

Script

function getview(x)
{
   var id = x; //Id will get here.
}

Upvotes: 0

user3559349
user3559349

Reputation:

Duplicate id attributes are invalid html. Remove the id attribute and the onclick and use

$('.ids').click(function() {
    var productId = $(this).closest("tr").find("td").eq(0).text();
});

Alternatively, add the value in a data attribute

<button type="button" class="ids" data-id="@prod.Pid"></button>

and use

$('.ids').click(function() {
    var productId = $(this).data('id');
});

Note that your current selector - $("#ProductGrid .ids") returns all the button elements, not the one you clicked.

Upvotes: 5

Nitesh Kumar
Nitesh Kumar

Reputation: 1774

Change the button tag like this

<td><button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview(@prod.Pid)"></button></td>

and the JS function like this

function getview(id) {
    debugger;
    var productId = id;
});

Upvotes: 0

Related Questions