如何通过mvc中的href链接将行id从视图传递到控制器

问题描述 投票:0回答:1

我想通过hv链接从mvc中的数据表传递行Id从视图到控制器。

这是我的数据表设计代码

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

这是数据表操作代码

$(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> ";
                }
            },
        ]
    });
});

这是控制器

[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");
}

现在在datatable动作代码中我​​尝试了以下代码

<a href='/ServiceJob/GetPrintById?'" + row.id + "'' class='btn btn-success btn-lg glyphicon glyphicon-print'> Print </a>

但上面的代码不起作用。

并且在href的位置,如果我使用了actionlink,那么那时它显示错误,即当前上下文中不存在行。

这是actionlink代码,

@Html.ActionLink("Print", "GetPrintById", "ServiceJob", new { id = row.id }, null)

所以,对我而言,代码都没有执行。

帮我解决这个问题。

谢谢。

asp.net-mvc razor datatables href actionlink
1个回答
1
投票

row是一个客户端变量,你不能在运行服务器端的@Html.ActionLink()帮助器中使用它。您可以使用@Url.Action()帮助器添加行ID,并将包含完整URL的变量设置为href设置中的锚标记的render属性:

"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> ";
}

更新:

请注意,锚标记始终使用GET请求来调用href属性中提到的控制器操作的路径,因此必须省略/删除控制器操作上的[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");
}

参考:

Datatables with asp.net mvc rendering Url.actions/html.actionlinks with route values

© www.soinside.com 2019 - 2024. All rights reserved.