0
我一直在試圖創建一個使用JSON調用刪除方法在我的控制器,但到目前爲止它不工作在MVC中刪除按鈕。刪除使用實體框架和呼叫控制器方法在阿賈克斯
我做陷阱腳本錯誤警報,併成功部分沒有登記的事情,我需要幫助以及這裏是我的看法,從使用實體框架5.1的SQL Server挑選數據。
我正在使用一個名爲Departments
的表,它有兩列,分別爲DepartmentId
和DepartmentName
。
<div class="container" style="width:40%; margin-top:2%;">
<hr />
<table class="table-responsive">
<tr>
<th>Deprtment Name</th>
<th></th>
</tr>
<tbody>
@if(ViewBag.RowDepartmentList != null)
{
foreach(var item in ViewBag.RowDepartmentList)
{
<tr id="[email protected]">
<td>@item.DepartmentId</td>
<td>@item.DepartmentName</td>
<td><a href="#" class="btn btn-danger" onclick="ConfirmDelete(@item.DepartmentId)">
<i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
}
}
</tbody>
</table>
<input type="hidden" id="HiddenDepartmentId" />
</div>
我添加了一個隱藏屬性捕捉DepartmentId
,形式也有一個刪除按鈕,首先要求刪除對話框模式。
我DELETE
對話框模式代碼:
<div class="modal fade" id="mymodal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" style="width:350px;">
<div class="modal-content">
<div class=" modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="close">
<span aria-hidden="true">x</span>
</button>
<h3 class="modal-title">Delete record</h3>
</div>
<div class="modal-body">
<h4>Are you sure you want to delete this?</h4>
</div>
<div class="modal-footer">
<a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a>
<a href="#" class="btn btn-success" onclick="DelDepartment()">Delete</a>
</div>
</div>
</div>
這是我的控制器是什麼樣子:
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult DepartmentIndex()
{
MVCTutorialEntities2 db = new MVCTutorialEntities2();
List<EmployeeViewModel> emlist = db.Departments.Where(x => x.IsDeleted == 0).Select(x => new EmployeeViewModel {DepartmentId=x.Departmentid, DepartmentName = x.DepartmentName }).ToList();
ViewBag.RowDepartmentList = emlist;
return View();
}
// the delete function
[HttpPost]
public JsonResult DelDepartment(int depId)
{
MVCTutorialEntities2 db = new MVCTutorialEntities2();
bool result = false;
Department dep = db.Departments.SingleOrDefault(x => x.Departmentid == depId);
if (dep != null)
{
db.Departments.Remove(dep); // I don't know why this is not deleting .... the table is not cascaded
db.SaveChanges();
result = true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
// now my script is all here that calls the
<script>
var ConfirmDelete = function (DepartmentId) {
$("#HiddenDepartmentId").val(DepartmentId);
$("#mymodal").modal("show");
}
var DelDepartment = function()
{
var depId = $("#HiddenDepartmentId").val();
$.ajax({
type: 'POST',
url: 'Employee/DelDepartment',
data: { DepartmentId: depId },
success: function (result) {$("#mymodal").modal("hide"); },
error: function (result) { alert(result); $("#mymodal").modal("hide"); } // only the error section resturns a message of [object] of [object]
});
}
</script>
千方百計想學習這門語言?如果是的話,有沒有方式我可以只用剃刀並撥打刪除功能
@using (Html.BeginForm("", "",FormMethod.POST)) ?
功能?