Reputation: 482
I want to pass row Id from view to controller via href link from datatable in mvc.
Here is my datatable design code
<table id="dataGrid" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>N</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
</table>
Here is the datatable action code
$(document).ready(function () {
$("#dataGrid").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"pageLength": 5,
"lengthMenu": [5, 10, 50, 100, 1000, 10000],
"columnDefs":
[{
"targets": [0],
"visible": false,
"searchable": false,
"orderable": false
}
],
"columns": [
{ "data": "id", "name": "Id", "autoWidth": true, "orderable": false },
{ "data": "date", "name": "Date", "autoWidth": true, "orderable": false, "format": "dd/MM/yyyy" },
"render": function (data, type, row) {
return " <a href='/ServiceJob/GetPrintById?'" + row.id + "'' class='btn btn-success btn-lg glyphicon glyphicon-print'> Print </a> ";
}
},
]
});
});
And here is the controller
[HttpPost]
public IActionResult GetPrintById(int id)
{
ServiceJobModel model = new ServiceJobModel();
// Service Job Detail
var serviceJob = _Db.ServiceJob.Where(x => x.Id == id).FirstOrDefault();
model.Id = serviceJob.Id;
model.Date = serviceJob.Date;
return View("Print");
}
Now in datatable action code I tried in return by the following code
<a href='/ServiceJob/GetPrintById?'" + row.id + "'' class='btn btn-success btn-lg glyphicon glyphicon-print'> Print </a>
but the above code is not working.
And in the place of href if I used the actionlink then at that time it showing the error i.e. row does not exist in the current context.
Here is the actionlink code,
@Html.ActionLink("Print", "GetPrintById", "ServiceJob", new { id = row.id }, null)
So , for me both the code is not executing.
Help me to solve this issue.
Thank You.
Upvotes: 1
Views: 6863
Reputation: 24957
The row
is a client-side variable and you can't use it inside @Html.ActionLink()
helper which runs server-side. You can add row ID by using @Url.Action()
helper and set the variable containing the complete URL into anchor tag's href
attribute inside render
setting:
"render": function (data, type, row) {
var url = '@Url.Action("GetPrintById", "ServiceJob")/' + row.id;
return "<a href='" + url + "' class='btn btn-success btn-lg glyphicon glyphicon-print'>Print</a> ";
}
Update:
Take note that anchor tag always uses GET request to call the path of controller action mentioned in href
attribute, hence the [HttpPost]
attribute on the controller action must be omitted/removed:
public IActionResult GetPrintById(int id)
{
ServiceJobModel model = new ServiceJobModel();
// Service Job Detail
var serviceJob = _Db.ServiceJob.Where(x => x.Id == id).FirstOrDefault();
model.Id = serviceJob.Id;
model.Date = serviceJob.Date;
return View("Print");
}
Reference:
Datatables with asp.net mvc rendering Url.actions/html.actionlinks with route values
Upvotes: 2