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

Javascript 如何为DataTable行单击事件绑定ActionLink?,javascript,jquery,asp.net-mvc,datatable,Javascript,Jquery,Asp.net Mvc,Datatable,我有一个服务器端数据表,当我单击每一行时,我希望它显示其Edit和Delete操作链接,供用户单击并指向这些页面 @*<td> @Html.ActionLink("Edit", "Edit", new { id = item.DepartmentID }) | @Html.ActionLink("Details", "Details", new { id = item.DepartmentID }) | @Html.ActionLin

我有一个服务器端数据表,当我单击每一行时,我希望它显示其
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>*@
我有
DT_RowId
获取我的数据的每个表行的id

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

当我的数据表中有它们时,我的数据表不会显示

列中的数字应与您拥有的数字匹配。据我所见,您指定了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>
部分观点:

@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>
打开模式后,将值发布到服务器以使用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");
            }
        });
    });
//工作经验编辑
$(“#公司编辑提交”)。单击(函数(){
//拿到表格
风险值形式=$(“#公司形式”);
//验证表单
如果(!form.valid()){
返回;
}
//序列化表单
serializedForm=form.serialize();
//阿贾克斯邮报
$.ajax({
url:“@url.Action(“CompanyEdit”、“CV”)”,
类型:“POST”,
数据:序列化格式,
beforeSend:函数(){
l、 ladda(“启动”);
},
成功:功能(结果){
如果(结果、成功){
//更新表的行
cTable.fnUpdate([
result.id,
result.name,
结果.title,
"" + " " + ""
],职位);
toastrSuccess(result.message);
}否则{
toastrError(result.message);
}
},
错误:函数(jqXHR、textStatus、errorshown){
toastrError(文本状态);
},
完成:函数(){
//停止ladda按钮加载
l、 拉达(“停止”);
//隐藏模态
$(“.modal”).modal(“隐藏”);
}
});
});
和您的编辑控制器

[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" });
    }
[HttpPost]
[ValidateAntiForgeryToken]
公共行动结果公司编辑(公司视图模型)
{
if(ModelState.IsValid)
{
var company=repository.FindCompany(model.CompanyId);
如果(公司!=null)
{
尝试
{
//地图自动制图器
model.Description=model.Description.Replace(Environment.NewLine,“
”); mapper.Map(模型、公司); 储存库。编辑公司(公司); 返回Json(新的{success=true,message=“Wokr Experience Edited”,id=company.CompanyId,title=company.JobTitle,name=company.CompanyName}); } 捕获(例外情况除外) { 返回Json(新的{success=false,message=string.Format(“{0}”,ex)}); } } 其他的 { 返回Json(新的{success=false,message=“未找到工作经验”}); } } 返回Json(新的{success=false,message=“模态状态无效”}); }
另一件需要提及的事情是,使用DisplayTemplate,而不是使用foreach循环

如果公司财产为IEnumerable,则 自动执行循环并呈现CompanyViewModel.cshtml 显示此集合中每个项目的模板


身份证件
单位
标题
行动
@DisplayFor(m=>m.companys)
身份证件
单位
标题
行动
并在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>
@model Taw.WebUI.Models.CompanyViewModel
@DisplayFor(m=>m.CompanyId)
@DisplayFor(m=>m.CompanyName)
@DisplayFor(m=>m.JobTitle)

谢谢,但要想让我的头脑清醒过来,只需点击
在线点击
事件来显示操作链接,似乎需要做很多工作。我对jQuery和datatables还比较陌生,所以我会更深入地研究它。是的,我也花了一段时间,但请记住,它基本上是获取视图/模式(razor+bootstrap模式)->为其提供一些数据(jQuery)->将数据发布到控制器(ajax)->保存数据(controller),其余就是您喜欢的方式,取决于你的喜好。我忘了再提一件事,如果dataTable不包含大量数据,就不需要真正的服务器端处理。
//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");
    });
//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" });
    }
<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>
@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>