首页 > 解决方案 > 单击时使 jQuery 数据表行成为 asp-action 链接

问题描述

我正在尝试创建一个 jQuery 数据表,当用户单击表行时,资产 ID 将传递给 ViewAsset 控制器。谢谢你的帮助

HTML 标记:

<table id="tblAsset">
 <thead >
    <tr>
        <th>
           Asset Name
        </th>
        <th>
           Asset Type
        </th>
        <th>
           Data Type
         </th>
   </tr>
   </thead>
   <tbody>

  @foreach (var item in Model)
   {
     // Onclick function for each row

     <tr onclick="ViewAsset(@item.Id)">

        <td>
         @Html.DisplayFor(modelItem => item.AssetName)
        </td>
        <td>
          @Html.DisplayFor(modelItem => item.AssetType)
         </td>

         <td>
         @Html.DisplayFor(modelItem => item.TypeofData)
         </td>
    </tr>
   }
  </tbody>
 </table>

jQuery 数据表

    <script type="text/javascript">
    $(document).ready(function () {
        $('#tblAsset').DataTable({
            "pageLength":10,
            "order": [[1, "asc"]],
        }
        );

    });

    // jQuery Function to call the controller

    function ViewAsset(id) {
        window.location.href = "Assets/ViewAsset/" + id;
    }
</script>

控制器动作链接

 <a asp-action="ViewAsset" asp-route-id="@item.Id">

标签: javascriptdatatableasp.net-core-mvc

解决方案


要处理每一行的点击事件,请为标签添加一个 onlick 事件。创建一个 js 函数并将您尝试访问的操作的 url 指定为参数。

//Razor view
<tr onclick='CallController("@Url.Action("ViewAsset", "YourController", new { id = "123" }))"'></tr>

//JS CODE 
function CallController(url){
        $.ajax({
            url: url,
            complete: function () {

            }
        });
}

推荐阅读