我正在尝试使用ajax在mvc.net中实现单页面应用程序,我遇到了实现删除服务的问题,这是我的删除操作方法:
[HttpPost]
public ActionResult Delete(int id)
{
Movie movie = db.Movies.Find(id);
db.Movies.Remove(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
这是我的删除onclick功能:
function Delete(id){
//here i want to take delete the row with it specifc id ,
$.ajax({
type: "POST",
url: '@Url.Action("Delete")',
data: JSON.stringify({ ID: id }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
// alert("Data has been deleted.");
LoadData();
},
error: function () {
alert("Error while deleting data");
}
});
单击删除按钮时应调用此删除,该按钮由加载数据函数创建:
function LoadData() {
$("#tblStudent tbody tr").remove();
$.ajax({
type: 'POST',
url: '@Url.Action("getStudent")',
dataType: 'json',
data: { id: '' },
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='prtoducttd' id='MovieID'>" + item.ID + "</td>"
+ "<td class='prtoducttd'>" + item.Name + "</td>"
+ "<td class='prtoducttd'>" + item.Type + "</td>"
+ "<td class='prtoducttd'>" + item.date + "</td>"
+ "<td class='prtoducttd'>" + "<input class='btn btn- primary' name='submitButton' id='btnEdit' value='Edit' onclick='delete' type='button'>"+ "<input class='btn btn- primary' name='submitButton' id='btnDel' value='Delete' type='button'>" + "</td>"
+ "</tr>";
$('#tblStudent tbody').append(rows);
});
},
单击按钮时如何将影片的id传递给删除功能?
答案 0 :(得分:0)
ajax需要一些修改。参数和方法名称的名称应该与controller和ajax完全匹配。
$.ajax({
type: "POST",
url: '/ControllerName/Delete',// same case sensitive action name
data: JSON.stringify({ id: id }), //small letter id, same as in controller parameter
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
// alert("Data has been deleted.");
LoadData();
},
error: function () {
alert("Error while deleting data");
}
&#13;
如果仍然没有调用删除操作,请删除json.stringify并在数据中传递&#39; id&#39;:idval。
答案 1 :(得分:0)
参数:ajax调用的{}必须相同,因为在Controller中使用公共ActionResult Delete(int id)必须在ajax调用中使用id:id。
$.ajax({
type: "POST",
url: '@Url.Action("Delete")',
data: JSON.stringify({ id: id }), //use id here
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
// alert("Data has been deleted.");
LoadData();
},
error: function () {
alert("Error while deleting data");
}
});
第二件事,在单个var行变量中写入加载数据函数中的整行并不是一个好主意。你可以声明var row =&#39;&#39 ;;在每个循环之前然后可以这样做。
var rows = '';
$.each(data, function (i, item) {
rows += "<tr>",
rows += '<td>' + item.MovieID+ '</td>'
//and so on.............and lastly use .html instead of append
$('#tblStudent tbody').html(rows);
});
供参考,请参阅此链接: - http://www.c-sharpcorner.com/article/crud-operation-in-asp-net-mvc-using-ajax-and-bootstrap/