簡體   English   中英

獲取從MVC表中單擊的行的ID

[英]Get Id of the row clicked from the table in MVC

我想在用戶單擊按鈕時單擊行Id

我的代碼如下。

   <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>

我試過了:-

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

但這是行不通的。

重復的id屬性是無效的html。 刪除id屬性和onclick並使用

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

或者,將值添加到data屬性中

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

和使用

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

請注意,當前選擇器- $("#ProductGrid .ids")返回所有按鈕元素,而不是您單擊的按鈕元素。

只需更新標簽即可。

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

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

它將為您提供腳本中的ID。

像這樣更改按鈕標簽

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

和這樣的JS函數

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

嘗試以下代碼。

視圖

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

腳本

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM