2011-12-19 108 views
1

我正在爲某個站點構建一個後臺,並且在這裏我需要使用ajax從數據庫中刪除註釋,問題是我不能傳遞我想要隱藏的id在Ajax中刪除jQuery。以下是評論的代碼:使用ajax mvc3傳遞參數給jquery .net

<% 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,但我相信有更好的解決方案

回答

1

假設你正在使用jQuery不顯眼的AJAX腳本,你可以傳遞參數給回調:

<%= Ajax.ActionLink(
    "Delete", 
    "Deletecomment", 
    new { 
     id = item.CommentID 
    }, 
    new AjaxOptions { 
     HttpMethod = "POST", 
     OnSuccess = "deleteRow('#row" + item.CommentID + "')" 
    } 
) %> 

然後:

function deleteRow(row) { 
    $(row).remove(); 
} 
2

你能不能在ID動態傳遞給回調:

new AjaxOptions { HttpMethod = "POST", OnSuccess = "function(){ return deleteRow('" + item.CommentID + "');" } 

function deleteRow(id) { 
    $("#row" + id).remove(); 
} 
相關問題