1

I am building a backoffice to a certain site, and here i need to delete the comments from the database using ajax, the problem is i cant pass the id i want to hide after deleting to jquery in ajax. following is the code for the comments:

<% 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>
<% } %>

this is the code for the controller:

[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");
    }

this is my jquery

function deleteRow() {
    var url_ = this.url.split("/");
    $("#row" + url_[url_.length - 1]).remove();
}

what i have done is taken the url and split it to take the id of the entry in db then add it to the form as id and then remove that id, but i am sure there is a better solution

2 Answers 2

2

can you not dynamically pass in the id to the callback:

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

function deleteRow(id) {
    $("#row" + id).remove();
}
1

Assuming you are using the jquery unobtrusive ajax script you could pass parameters to the callback:

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

and then:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.