我正在为某个网站建立一个后台,在这里我需要使用ajax从数据库中删除注释,问题是我无法传递我想要在删除到ajax中的jquery后隐藏的id。以下是评论的代码:
<% foreach (var item in Model) { %>
<div class="row" id = "row<%= item.CommentID %>">
<div class="editor-label detail">Comment</div>
<div class="form-element"><%: Html.DisplayFor(modelItem => item.Text) %></div>
<div class="editor-label detail">Date</div>
<div class="form-element"><%: Html.DisplayFor(modelItem => item.Date) %></div>
<div class="form-element">
<div class="button delete"><%: Ajax.ActionLink("Delete", "Deletecomment", new { id = item.CommentID }, new AjaxOptions { HttpMethod = "POST", OnSuccess = "deleteRow" })%></div>
</div>
</div>
<% } %>
这是控制器的代码:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Deletecomment(int id)
{
cr.Delete(cr.getComment(id)); //cr is the conx to the repository
cr.Save();
return View("Index");
}
这是我的jquery
function deleteRow() {
var url_ = this.url.split("/");
$("#row" + url_[url_.length - 1]).remove();
}
我所做的是取url并拆分它以获取db中的条目的id然后将其作为id添加到表单然后删除该id,但我确信有更好的解决方案
答案 0 :(得分:2)
你能不能动态地将id传递给回调:
new AjaxOptions { HttpMethod = "POST", OnSuccess = "function(){ return deleteRow('" + item.CommentID + "');" }
function deleteRow(id) {
$("#row" + id).remove();
}
答案 1 :(得分:1)
假设您正在使用jquery unobtrusive ajax脚本,您可以将参数传递给回调:
<%= Ajax.ActionLink(
"Delete",
"Deletecomment",
new {
id = item.CommentID
},
new AjaxOptions {
HttpMethod = "POST",
OnSuccess = "deleteRow('#row" + item.CommentID + "')"
}
) %>
然后:
function deleteRow(row) {
$(row).remove();
}