[英]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">×</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.