I am using BeginCollectionItem to dynamically add items to a list. If I attempt click a newly added row, the app immediately halts and redirects me to the login page. If I delete an item that already existed, it deletes it from the database, then deletes it from the UI, then redirects me to the login page. If the item is newly added, it does not even run the code in the delete.onClick at all the other does, but they both end up with redirecting me to the login screen.
I had a similar problem when trying append the div and was told to add:
e.preventDefault();
e.stopImmediatePropagation();
I tried that but it did not stop my app from halting and redirecting to the login page. Here is my delete code:
$("a.deleteRow").on("click", function (e) {
var container = $(this).closest('.editorRow');
var id = container.data('id');
var $t = $(this);
$.ajax({
type: "POST",
url: "@Url.Action("Delete","Request", new { area = "" })",
data: { CommentId: id },
success: function (e) {
$t.parents("div.editorRow:first").remove();
e.preventDefault();
e.stopImmediatePropagation();
}
})
return false;
});
Here is the partial view:
@using (Html.BeginCollectionItem("Comments"))
{
<div class="row editorRow" data-id="@Model.Id" style="padding-bottom:10px">
@Html.HiddenFor(x => x.Id)
<div class="col-xl-2">
@if (Model.CreatorName == "" || Model.CreatorName == null)
{
Html.DisplayFor(x => x.CreatorName, (string)@ViewBag.UserName);
}
else
{
@Html.DisplayFor(x => x.CreatorName)
}
</div>
<div class="col-xl-8">
@Html.TextAreaFor(x => x.Comment, new { @class = "form-control" })
</div>
<div class="col-xl-2">
<a href="#" class="deleteRow">delete</a>
</div>
</div>
}
here is Delete code in Controller:
public ActionResult Delete(int CommentId)
{
service.DeleteComment(CommentId);
return Content("" + CommentId);
}
Update:
After putting the delete code in document.ready, the ajax portion deleting the existing row now works fine. However, attempting to add and delete a row without first saving that row is still redirecting. The new delete code which now works with an "existing" row is as follows:
$(document).ready(function () {
$("a.deleteRow").on("click", function (e) {
var container = $(this).closest('.editorRow');
var id = container.data('id');
var $t = $(this);
$.ajax({
type: "POST",
url: "@Url.Action("Delete","Request", new { area = "" })",
data: { CommentId: id },
success: function (e) {
$t.parents("div.editorRow:first").remove();
return false;
}
})
return false;
});
});
I am new to jQuery and am trying to understand as well as get my project working.
Looking at the code I cannot see that this redirection is related to jquery. Can you take a look at the RequestController and Delete action. Most likely your Delete Action in controller is doing the redirection in this case after it has deleted the record from database.