7

I have been searching for the last few hours, and unfortunately I cannot seem to find an example of how to populate a datatable with an action edit and delete link column using .net and MVC.

Here is what I have so far, how do I add an action link? What am I missing?

<script type="text/javascript">
$(document).ready(function () {
    $('#myDataTable').dataTable({
        bProcessing: true,
        sAjaxSource: '@Url.Action("Index1", "Default1")'
    });

});
</script>

<div id="container">
<div id="demo">
    <table id="myDataTable">
        <thead>
            <tr>
                <th>
                    RoleId
                </th>
                <th>
                    RoleName
                </th>
                <th>
                    UserId
                </th>
                <th>
                    UserName
                </th>
            </tr>
        </thead>
        <tbody> 
        </tbody>
</table>    
</div>
</div>

I want to add this in the last column;

    <td>
        @Html.ActionLink("Edit", "Edit", new {id=item.PrimaryKey}) |
        @Html.ActionLink("Details", "Details", new { id=item.PrimaryKey }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.PrimaryKey })
    </td>

But cannot figure out how to do it.

madth3
  • 7,275
  • 12
  • 50
  • 74
nitefrog
  • 1,760
  • 6
  • 31
  • 59

7 Answers7

17

You could use the aoColumns property with fnRender function to add custom columns. You can't use the Html.ActionLink helper because you have to generate the links dynamically from the javascript. The aoColumns property helps you to configure each columns, if you don't want to configure a particular column just pass null else you have to pass an object({}).

The fnRender function helps you to create the links using the values of the other columns. You can use the oObj.aData to get the values of the other column like id to generate the links.

<script type="text/javascript">    
    $(document).ready(function () {
        $('#myDataTable').dataTable({
            bProcessing: true,         
            sAjaxSource: '@Url.Action("Index1", "Default1")',
            aoColumns: [
                      null, // first column (RoleId)
                      null, // second column (RoleName)  
                      null, // third (UserId)
                      null, // fourth (UserName)

                      {     // fifth column (Edit link)
                        "sName": "RoleId",
                        "bSearchable": false,
                        "bSortable": false,
                        "fnRender": function (oObj)                              
                        {
                            // oObj.aData[0] returns the RoleId
                            return "<a href='/Edit?id=" 
                                + oObj.aData[0] + "'>Edit</a>";
                        }
                       },

                       { }, // repeat the samething for the details link

                       { }  // repeat the samething for the delete link as well

                   ]
     });  
}); 
</script>

Another important thing in the JSON output you return from the server, for the edit column also you have to return something like 1, 2, 3 or anything.

Reference: http://jquery-datatables-editable.googlecode.com/svn/trunk/ajax-inlinebuttons.html

Igorek
  • 15,716
  • 3
  • 54
  • 92
VJAI
  • 32,167
  • 23
  • 102
  • 164
  • 5
    "fnRender" has been deprecated. Use "mRender" instead. http://www.datatables.net/usage/columns – asunrey Mar 06 '13 at 17:23
7

The fnRender has been depreciated and the mRender doesn't received the same parameters.

This works for me, follow the @Mark example:

  {     // fifth column (Edit link)
    "sName": "RoleId",
    "bSearchable": false,
    "bSortable": false,
    "mRender": function (data, type, full) {
        var id = full[0]; //row id in the first column
        return "<a href='javascript:alert("+id+");'>Edit</a>";
   }
Fernando JS
  • 4,267
  • 3
  • 31
  • 29
3

The other responses are using legacy DataTables syntax. For DataTables 1.10+, the syntax for columnDefs is as follows:

$('#MyDataTable').DataTable({
    "processing": true,
    "ajax": '@Url.Action("Index1", "Default1")',
    "columnDefs": [
        {"targets": [4], "data": "RoleId", "render" : function(data, type, full) { return '@Html.ActionLink("Edit", "Edit", new {id = "replace"})'.replace("replace", data);}},
        {},  //repeat
        {}   //repeat
    ]
});

note: In order to get the Model in the ActionLink, I'm using JavaScript replace() to replace the string "replace" with data, which is defined as "RoleId" earlier in the columnDef

devlin carnate
  • 8,309
  • 7
  • 48
  • 82
2

Another approach with aoColumnDefs

$('#myDataTable').dataTable({
    bProcessing: true,
    sAjaxSource: '@Url.Action("Index1", "Default1")'
    aoColumnDefs: [{
                     "aTargets": [4],    //Edit column
                     "mData": "RoleId",  //Get value from RoleId column, I assumed you used "RoleId" as the name for RoleId in your JSON, in my case, I didn't assigned any name in code behind so i used "mData": "0"
                     "mRender": function (data, type, full) {
                       return '<a href=' +
                            '@Url.Action("Edit", "Default1")?RoleId=' + data +
                            '>Edit</a>';
                     }
                  },{
                     "aTargets": [5],    //Detail column
                     "mData": "RoleId",  
                     "mRender": function (data, type, full) {
                       return '<a href=' +
                            '@Url.Action("Detail", "Default1")?RoleId=' + data +
                            '>Detail</a>';
                     }
                  },{
                     "aTargets": [6],    //Delete column
                     "mData": "RoleId",  
                     "mRender": function (data, type, full) {
                       return '<a href=' +
                            '@Url.Action("Delete", "Default1")?RoleId=' + data +
                            '>Delete</a>';
                     }
                  }]
});
bsting
  • 154
  • 4
1

I found another way to get this actionlink works using help from this post (olivier comments):

you add data tags attributes in the table node that you reuse in the Javascript

in cshtml:

<table class="table table-striped display" id="list" 
            data-url-edit="@Url.Action("Edit","User", new { id = "replace"})" 

in your *.js file in ths columndefs area:

  "columnDefs": [
        {
            "targets": [-1], "data": "UserID", "render": function (data, type, row, meta) {
                return '<a href="' + $('#list').data('url-edit').replace("replace", row.UserID) + '">Edit</a> | '
                    + '<a href="' + $('#list').data('url-details').replace("replace", row.UserID) + '">Details</a> | '
0

I have used mentioned code for datatable 1.10+ but get string in the datatable cell instead of the link.

@Html.ActionLink("Edit", "Edit", new {id = "294"})

note that using and old mvc3 version on the solution Here my javascript:

$(document).ready(function () {

var tenantid = $('#tenantid').text();
$("#title").html("<h1>User List for TenantID: "+ tenantid + " </h1>");

var oTable = $('#list').DataTable({
    "serverSide": true,
    "ajax": {
        "type": "POST",
        "url": '/User/DataHandler',
        "contentType": 'application/json; charset=utf-8',
        'data': function (data)
        {
            data.ID = tenantid;
            return data = JSON.stringify(data);
        }
    },
    "dom": 'lfrtiSp',        
    "processing": true,
    "paging": true,
    "deferRender": true,        
    "pageLength": 10,
    "lengthMenu": [5, 10, 25, 50, 75, 100],
    "columnDefs": [
        { "targets": [-1], "data": "UserID", "render": function (data, type, row, meta) { return '@Html.ActionLink("Edit", "Edit", new {id = "replace"})'.replace("replace", row.UserID); } }

    ],

    "columns": [
        { "data": "UserID", "orderable": true },
        { "data": "UserGUID", "orderable": false },
        { "data": "UserName", "orderable": true },
        { "data": "UserEMAil", "orderable": true },
        { "data": "UserIsDeleted", "orderable": true },
        { "data": "Action", "orderable": false }
    ],

    "order": [0, "asc"]

    });
 });
0

this works for me

add this as your Edit / Action column

{ "data": "YOURIDKEYCOLUMN",
  "render": function (data) {
   return "<a href='/YOUREDITINGURL/Edit/"+data+"'>Edit</a>"
   } 
Naveed Ahmed
  • 463
  • 4
  • 11