如何绑定ActionLink for DataTable行单击事件?

时间:2017-03-16 00:54:43

标签: javascript jquery asp.net-mvc datatable

我有一个服务器端dataTable,当我点击每一行时,我希望它显示其EditDelete操作链接,供用户点击它并指向这些页面。

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

当我在他们的网站上搜索时,他们使用editor作为数据表。但是我无法使用编辑器为许多未定义的错误实现actionlinks。

有人可以帮我弄清楚如何使点击活动有效吗?

这是dataTable的脚本

     init: function () {
       dt = $('#datatableServer').DataTable({
                    "serverSide": true,
                    "processing": true,
                    "ajax": {
                        "url":
                        "@Url.Action("DataHandler","Department")"
                    },
                    "columns": [
                        { "data": "Name",
                        "searchable": true },
                        {
                         "data": "Budget", "render": $.fn.dataTable.render.number(',', '.', 0, '$'),
                        "searchable": false },
                        { "data": "StartDate",
                            "searchable": false,
                            "type" : "datetime"},
                        { "data": "Administrator",
                        "searchable": true }
                    ],
                 ............ 
               departmentsList.init();});


$('#datatableServer tbody').on('click', 'tr', function () {

            //editor.edit(this, 'Edit record', {
                //"label": "Update",
                //"fn": function () {
                    //editor.submit()
                //}
            //})
            console.log('clicked');
            console.log(dt.row(this).data().DT_RowId);  // DT_RowId is each row's Id
        });

我让DT_RowId为我的数据获取每个表行的id。

var data = query.Select(a => new DepartmentData
                {
                    DT_RowId = a.DepartmentID.ToString(),
                    Name = a.Name,
                   ..........
                }).ToList();

1 个答案:

答案 0 :(得分:0)

首先是

  

当我将它们放入my时,我的dataTable不显示。

列中的数字应与您拥有的数字相匹配。从我所看到的,你指定了4列

"columns": [
    { "data": "Name", "searchable": true },
    { "data": "Budget", "render": $.fn.dataTable.render.number(',', '.', 0, '$'), "searchable": false },
    { "data": "StartDate", "searchable": false, "type" : "datetime"}, 
    { "data": "Administrator", "searchable": true }
]

但您还有一个操作列,其中包含您的Actionlinks。所以我建议添加一个附加数据列

{ data: "Action" }

另外请确保您还有五个标题列

<thead>
    <tr>
        <th>Name</th>
        <th>Budget</th>
        <th>StartDate</th>
        <th>Administrator</th>
        <th>Action</th>
    </tr>
</thead>

现在接下来的事情,我还没有尝试过使用他们的编辑器,我这样做的方式是使用我自己的模态,任何模态都可以,bootstrap模态是一个不错的选择。

例如,您在dataTable视图中指定了一个模态,我将它放在页面的末尾

<div id="companyModal" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h3 id="myCompanyModalLabel"></h3>
            </div>
            @{Html.RenderAction("CompanyModal", "CV");}
        </div>
    </div>
</div>

我喜欢在我的模态中使用ViewModal,所以我使用RenderAction从ViewModal验证中获取所有好东西。当然,如果你想在返回ViewModel之前获取ViewModel的值,你也可以使用@ Html.Partial()代替RenderAction,RenderAction。

 [ChildActionOnly]
 public ActionResult CompanyModal()
 {
    var model = new CompanyViewModel();
    return PartialView("~/Views/Dashboard/CV/_CompanyModal.cshtml", model);
 }

部分视图:

@model XXX.CompanyViewModel

<form id="companyForm" style="margin: 0px;">
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.HiddenFor(m => m.CompanyId)
        <div class="row-fluid">
            <div class="span6">
                @Html.LabelFor(m => m.CompanyName)
                @Html.TextBoxFor(m => m.CompanyName, new { @class = "input-block-level" })
                @Html.ValidationMessageFor(m => m.CompanyName)
            </div>
            <div class="span6">
                @Html.LabelFor(m => m.JobTitle)
                @Html.TextBoxFor(m => m.JobTitle, new { @class = "input-block-level" })
                @Html.ValidationMessageFor(m => m.JobTitle)
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
        <button id="companyEditSubmitBtn" name="edit" class="ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" type="button">Save</button>
    </div>
</form>

现在进入剧本:

//init dataTable
var cTable = $("#company-table").dataTable();

//open work experience edit modal
$("#company-table").on("click", ".companyEditBtn", function () {
        //do
        $("#myCompanyModalLabel").text("Edit Work Experience");

        //get current position
        position = cTable.fnGetPosition((this).closest("tr"));
        data = cTable.fnGetData(position);

        //set values to modal
        $("#companyModal #CompanyId").val(data[0]);
        $("#companyModal #CompanyName").val(data[1]);
        $("#companyModal #JobTitle").val(data[2]);

        //open modal
        $("#companyModal").modal("show");
    });

打开模态后,将值发布到服务器以使用ajax保存:

//work experience edit
$("#companyEditSubmitBtn").click(function () {
        //get the form
        var form = $("#companyForm");
        //validate form
        if (!form.valid()) {
            return;
        }
        //serialize the form
        serializedForm = form.serialize();

        //ajax post
        $.ajax({
            url: "@Url.Action("CompanyEdit", "CV")",
            type: "POST",
            data: serializedForm,
            beforeSend: function () {
                l.ladda("start");
            },
            success: function (result) {
                if (result.success) {
                    //update row of table
                    cTable.fnUpdate([
                        result.id,
                        result.name,
                        result.title,
                        "<button class='companyEditBtn btn' title='Edit Work Experience'><i class='icon-pencil'></i></button>" + " " + "<button class='companyDeleteBtn btn' title='Delete Work Experience'><i class='icon-trash'></i></button>"
                    ], position);

                    toastrSuccess(result.message);
                } else {
                    toastrError(result.message);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastrError(textStatus);
            },
            complete: function () {
                //stop ladda button loading
                l.ladda("stop");
                //hide modal
                $(".modal").modal("hide");
            }
        });
    });

和你的编辑控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CompanyEdit(CompanyViewModel model)
{
        if (ModelState.IsValid)
        {
            var company = repository.FindCompany(model.CompanyId);

            if (company != null)
            {
                try
                {
                    //map automapper
                    model.Description = model.Description.Replace(Environment.NewLine, "<br />");
                    mapper.Map(model, company);

                    repository.EditCompany(company);
                    return Json(new { success = true, message = "Wokr Experience Edited", id = company.CompanyId, title = company.JobTitle, name = company.CompanyName });
                }
                catch (Exception ex)
                {
                    return Json(new { success = false, message = string.Format("{0}", ex) });
                }
            }
            else
            {
                return Json(new { success = false, message = "Work Experience not found" });
            }
        }
        return Json(new { success = false, message = "Modal state is not valid" });
    }

另外要提到的是,使用DisplayTemplate,

而不是使用foreach循环
  

其中Companies属性是IEnumerable   自动执行循环并呈现CompanyViewModel.cshtml   显示此集合中每个项目的模板。

Source here

<table id="company-table" class="table table-striped table-bordered table-hover dataTables" width="100%">
    <thead>
        <tr>
            <th>ID</th>
            <th>Company</th>
            <th>Title</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @Html.DisplayFor(m => m.Companies)
    </tbody>
    <tfoot>
        <tr>
            <th>ID</th>
            <th>Company</th>
            <th>Title</th>
            <th>Action</th>
        </tr>
    </tfoot>
</table>

并在共享内指定您的显示模板 - &gt; DisplayTemplates - &gt; CompanyViewModel.cshtml

@model Taw.WebUI.Models.CompanyViewModel

<tr>
    <td>
        @Html.DisplayFor(m => m.CompanyId)
    </td>
    <td>
        @Html.DisplayFor(m => m.CompanyName)
    </td>
    <td>
        @Html.DisplayFor(m => m.JobTitle)
    </td>
    <td>
        <button class="companyEditBtn btn" title="Edit Work Experience"><i class="icon-pencil"></i></button>
        <button class='companyDeleteBtn btn' title="Delete Work Experience"><i class="icon-trash"></i></button>
    </td>
</tr>