简体   繁体   中英

Make jQuery datatable row an asp-action link when clicked

I am trying to create a jQuery datable that when user clicked on a table row the asset Id is passed to the ViewAsset controller. Thanks for your help

HTML markup:

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

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

Controller action link

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

To handle a click event for every row add an onlick event for the tag. Create a js function and specify as the parameter the url of the action you're trying to reach.

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

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

            }
        });
}

If you want to redirect to other view when click the row, you can directly use window.location.href to acces the controller action.

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

Scripts:

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

    });

    function ViewAsset(id) {
        window.location.href = "ControllerName/ActionName/" + id; 
    }

</script>

I found a better way to solve the issue. Post for people with similar issue in the future

<tr style="cursor: pointer;" onclick="location.href ='@(Url.Action("ViewAsset", "Assets", new { id = item.Id}))'">  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM