2012-06-29 21 views
7

Ho cercato le ultime ore, e sfortunatamente non riesco a trovare un esempio di come popolare un datatable con un'azione di modifica ed eliminare la colonna di collegamento usando .net e MVC.collegamento dati jQuerylink come aggiungere

Ecco cosa ho finora, come posso aggiungere un link di azione? Cosa mi manca?

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

Voglio aggiungere questo nell'ultima colonna;

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

Ma non riesco a capire come farlo.

risposta

17

È possibile utilizzare la proprietà aoColumns con la funzione fnRender per aggiungere colonne personalizzate. Non è possibile utilizzare l'helper Html.ActionLink perché è necessario generare i collegamenti dinamicamente dal javascript. La proprietà aoColumns consente di configurare ciascuna colonna, se non si desidera configurare una colonna specifica, basta passare null, altrimenti è necessario passare un object({}).

La funzione fnRender consente di creare i collegamenti utilizzando i valori delle altre colonne. È possibile utilizzare oObj.aData per ottenere i valori dell'altra colonna come id per generare i collegamenti.

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

Un'altra cosa importante nell'output JSON si ritorna dal server, per la colonna di modifica anche si deve tornare qualcosa come 1, 2, 3 o niente.

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

+5

"fnRender" è stato sconsigliato. Usa invece "mRender". http://www.datatables.net/usage/columns – asunrey

7

Il fnRender è stato svalutato e il mRender non ha ricevuto gli stessi parametri.

Questo funziona per me, seguire l'esempio @ Marco:

{  // 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>"; 
    } 
2

Un altro approccio con 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>'; 
        } 
        }] 
}); 
3

Le altre risposte sono utilizzando la sintassi DataTable legacy. Per DataTable 1.10+, la sintassi per columnDefs è la seguente:

$('#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 
    ] 
}); 

nota: Al fine di ottenere il modello nel ActionLink, sto usando JavaScript replace() per sostituire la stringa "sostituire" con data, che è definito come "RoleId" in precedenza nella colonnaDef

0

Ho usato il codice indicato per datatable 1.10+ ma ottenere la stringa nella cella datatable anziché il collegamento.

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

nota che l'utilizzo e la vecchia versione MVC3 sulla soluzione Qui il mio 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

ho trovato un altro modo per ottenere questo ActionLink funziona utilizzando l'aiuto di questo post (commenti Olivier):

aggiungi attributi tag di dati nel nodo tabella che riutilizzi in Javascript

in cshtml:

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

nel file di vostro * .js nella zona THS columndefs:

"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> | ' 
Problemi correlati