简体   繁体   English

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

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

I have a server-side dataTable where when I click each row, I want it to show its Edit and Delete action links for the user to click on it and be directed to those pages. 我有一个服务器端数据表,当我单击每一行时,我希望它显示其“ 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>*@

When I search on their website, they use the editor for datatables. 当我在他们的网站上搜索时,他们使用editor来获取数据表。 But I am not able to implement the actionlinks with the editor for many undefined errors. 但是对于许多未定义的错误,我无法通过编辑器实现操作链接。

Can someone please assist me to figure out how to make the on click event work? 有人可以帮我弄清楚如何使点击事件起作用吗?

This is the script for the dataTable 这是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
        });

I have the DT_RowId getting the id for each table row for my data. 我有DT_RowId获取我的数据的每个表行的ID。

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

First thing first 首先第一件事

When I have them in my , my dataTable does not show. 当我将它们放入时,不会显示我的dataTable。

The number in your column should match the number of you have. 您栏中的数字应与您拥有的数字相匹配。 From what i can see, you specified 4 columns 从我所看到的,您指定了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 }
]

but you also have an action column where your Actionlinks sit. 但是您还有一个“操作”列,您的“操作链接”位于其中。 So i suggest adding an addtional data column 所以我建议添加一个附加数据列

{ data: "Action" }

Also make sure your have five header columns too 还要确保您也有五个标题列

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

Now next thing, i haven't acutally tried to use their editor before, the way i do it is to use my own modal, any modal will do, bootstrap modal is an good option. 现在,接下来,我以前从未尝试过使用其编辑器,我的方式是使用自己的模式,任何模式都可以,引导模式是一个不错的选择。

For example, you specify a modal in your dataTable view, I place it at the end of the page 例如,您在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>

I like to use ViewModal in my modal, so i do RenderAction to get all the goodies from ViewModal validation. 我喜欢在模态中使用ViewModal,因此我执行RenderAction来从ViewModal验证中获取所有好处。 Of course, you can do @Html.Partial() too instead of RenderAction, RenderAction only if you want to get some value for the ViewModel before returning it. 当然,也可以只使用@ Html.Partial()来代替RenderAction和RenderAction,前提是您想在返回ViewModel之前为其获取一些值。

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

The partial view: 部分视图:

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

Now on to the script: 现在来看脚本:

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

After you open the modal, post the value to your server to save using ajax: 打开模式后,将值发布到服务器以使用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");
            }
        });
    });

And your edit controller 还有你的编辑控制器

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

Another thing to mention, instead of using a foreach loop, use DisplayTemplate, 还要提及的另一件事,是使用DisplayTemplate而不是使用foreach循环,

where the Companies property is an IEnumerable which will automatically do the looping and render the CompanyViewModel.cshtml display template for each item of this collection. 其中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>

And specify your display template inside Shared -> DisplayTemplates -> CompanyViewModel.cshtml 并在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.

相关问题 jQuery:如何将onClick事件绑定到DataTable行? - jQuery : How to bind an onClick Event to a DataTable row? Angular - 数据表点击行事件 - Angular - Datatable click row event 如何检测DataTable子行内的按钮单击事件? - How to detect button click event inside DataTable child row? 如何在iOS中绑定点击事件? - How to bind a click event in iOS? 如何使用 vue.js 中的单击事件从数据表中删除行而不干扰计算的 function - How to delete row from datatable without interfering a computed function using a click event in vue.js 如何在每个表行上放置click事件并将结果作为参数传递,以将新数据绑定到另一个源? - How to place click event on each table row and pass result as argument to bind new data to another source? 在 YUI 数据表中最后点击的行上调用点击事件 - Call click event on last clicked row in YUI datatable 如何在click事件中附加数据来自dataTable - How to append the data From dataTable in click event 当按钮:[&#39;colvis&#39;] 激活时,复选框单击事件在数据表行中不起作用 - Checkbox click event not working in datatable row when buttons: [ 'colvis' ] activeted jQuery click事件上的jQuery Datatable访问行数据(render参数) - jQuery Datatable access row data ( render parameter ) on jQuery click event
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM