需要将列表中的项目 ID 与 bootstrap 按钮相关联

Need to assoicate an item id from a list with a bootstrap button

我在 MVC 模型中循环时有一个记录列表(请参阅下面代码中的 "for each" 循环)。

我希望能够 将 Bootstrap 组件与被单击记录的 ID 相关联 ,而不是使用 ActionLink 并链接到另一个页面调出模态形式。

我知道如何调出和关联模态形式除了将 ID 值关联到列表中我需要的任何组件。

我正在考虑如下 某事,但我需要一些关于要使用的 确切组件以及如何关联记录的 ID 值的帮助被点击了。

带有路由值和 html 属性的 ActionLink 只是一个有根据的猜测...

如有任何帮助,我们将不胜感激...

@model IEnumerable<YeagerTechDB.Models.Category>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CategoryDescription)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CategoryDescription)
        </td>
        <td>
            @*insert a specific bootstrap component instead of actionlinks???*@
            @*when component clicked, assoicate record id in list, bring up modal form and execute associated JS*@
            @*if using just a button below, how do i associate the id of the item that was clicked?*@
            <button type="button" class="btn btn-default btn-lg">
                <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Edit
            </button>
            @Html.ActionLink("<span class='glyphicon glyphicon-edit'></span>", "Edit", "Edit", routeValues: new { id = item.CategoryID }, htmlAttributes: new { data_modal = "", @class = "btn btn-default" })
            @*@Html.ActionLink("Edit", "Edit", new { id = item.CategoryID })*@
         </td>
    </tr>
}

    @*bootstrap modal screen inserted here*@
    @*have hidden id field in modal form*@

</table>

简单的方法是使用 data- 属性。由于您在每一行上都有多个用于客户端 UI 的按钮,因此您可以使用 <tr> 来存储相关数据,或者将其存储在每个按钮上。

我在 asp 工作不多,所以语法可能不准确,但看起来像:

<tr data-id="<% item.id %>"> 

然后在您的按钮点击处理程序中,您可以使用以下方法访问行数据:

$('.buttonClass').click(function(){
    var rowId = $(this).closest('tr').data('id');
    /* do stuff with modal */
});

参考:data() API docs