繁体   English   中英

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

[英]How to bind an ActionLink for DataTable row click event?

我有一个服务器端数据表,当我单击每一行时,我希望它显示其“ Edit和“ Delete操作链接,以供用户单击并指向这些页面。

    @*<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来获取数据表。 但是对于许多未定义的错误,我无法通过编辑器实现操作链接。

有人可以帮我弄清楚如何使点击事件起作用吗?

这是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();

首先第一件事

当我将它们放入时,不会显示我的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 }
]

但是您还有一个“操作”列,您的“操作链接”位于其中。 所以我建议添加一个附加数据列

{ data: "Action" }

还要确保您也有五个标题列

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

现在,接下来,我以前从未尝试过使用其编辑器,我的方式是使用自己的模式,任何模式都可以,引导模式是一个不错的选择。

例如,您在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验证中获取所有好处。 当然,也可以只使用@ Html.Partial()来代替RenderAction和RenderAction,前提是您想在返回ViewModel之前为其获取一些值。

 [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显示模板。

来源在这里

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

并在Shared-> DisplayTemplates-> 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM