Delete by MVC ID 5

I use BeginCollectionItem with MVC 5 to add and remove rows every time.

I have a problem with the delete function, I followed the online tutorial which is indicated using #divId: first, which seems to indicate the removal of the first line every time. This is not good for me and does not make sense to the end user.

Since I use BCI, I want to remove them from the html DOM so that they do not have database identifiers.

How to remove the model identifier, this, apparently (I think I read somewhere), is automatically generated by BCI?

Delete function in main view

$('#deleterow').live('click', function () {
            $(this).parents('#newRow:first').remove();
            return false;
        });

Partial view with lines I want to delete by Id

@model  Mvc.Models.Project
@using (Html.BeginCollectionItem("something"))
{
    <div id="newRow">
        @Html.LabelFor(m => m.Name)
        @Html.EditorFor(m => m.Name)

        <a href="#" id="deleterow">Delete</a>
    </div>
}

Update 2

html data-action 0 , JQuery / .

" ", , ? jQuery, , , MVC, , :

<h3>Students</h3>
<div id="newStudent">
    @foreach(var Student in Model.students)
    {
        Html.RenderPartial("_Student");
    }
</div>
<input type="button" id="addStudent" name="addStudent" value="Add Student"/>

<input type="submit" value="Submit"/>
@section Scripts
{
    <script type="text/javascript">
        $('#addStudent').on('click', function () {
        $.ajax({
            async: false,
            url: 'School/AddNewStudent'
        }).success(function (partialView) {
            $('#newStudent').append(partialView);
        });
    });

    $('#newStudent').on('click', '.deleteStudent', function () {
        var id = $(this).data('id');
        if (id === 0) { // assumes Id is integer
            $(this).closest('.studentRow').remove();
        }
        else { // existing item - controller to delete from Db
            var url = '@Url.Action("action", "controller")';
            $.post(url, { ID: id }, function (response) {
                if (response) {
                    $(this).closest('.studentRow').remove();
                }
            }).fail(function (response) {
                // display error message
            });
        }
    });
    </script>
}

@using (Html.BeginCollectionItem("students"))
{
    <div id="studentRow">
        @Html.HiddenFor(m => m.Id)
        @Html.LabelFor(m => m.Name)
        @Html.EditorFor(m => m.Name)

        <a href="#" class="deleteStudent" data-action="@Model.Id">Delete</a>
    </div>

}

public class SchoolController : Controller
{
    // GET: School
    public ActionResult Index()
    {
        var newSchool = new School();

        return View(newSchool);
    }

    public ActionResult AddNewStudent()
    {
        var student = new Student();
        return PartialView("_Student", student);
    }
    [HttpPost, ActionName("DeleteStudent")]
    public ActionResult DeleteStudent(School school)
    {
        foreach(var student in school.students.Where(s => !s.isDeleted))
        {
            return View(school.students);
        }

        return View();
    }
}
+4
2

-, .live() jquery-1.7 1.9. .on(). HTML, id "", , - , , , , BeginCollectionItem _ ID_. , , , guid, .

id, script.

@using (Html.BeginCollectionItem("students"))
{
    <div id="studentRow">
        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.isDeleted) // not sure what the point of the data- attribute is
        @Html.LabelFor(m => m.Name)
        @Html.EditorFor(m => m.Name)
        <a href="#" class="deleteStudent" data-id="@Model.Id">Delete</a>
    </div>
}

script ( , id="newStudent" <div> , foreach html )

$('#newStudent').on('click', '.deleteStudent', function() { // use event delegation
    var id = $(this).data('id');
    if (id == 0) { // assumes property Id is typeof int
        // Its a new item so just remove from the DOM
        $(this).closest('.studentRow').remove();
    } else {
        // Its an existing item so call controller to delete it from the database
        var url = '@Url.Action(""DeleteStudent", "School")';
        $.post(url, { ID: id }, function(response) {
            if(response) {
                // The student was successfully deleted
                $(this).closest('.studentRow').remove();
            }
        }).fail(function (response) {
            // Oops, something went wrong - display error message?
        });
    }
});

[HttpPost]
public JsonResult DeleteStudent(int ID)
{
    // delete the student from the database based on the ID and signal success
    return Json(true);
}
+3

IsDeleted Model/ViewModel, , Row

 using (Html.BeginCollectionItem("Contacts"))
    {
        <div class="row mt-10">
            @Html.HiddenFor(m => m.Id)
            @Html.HiddenFor(m => m.isDeleted, new { data_is_deleted = "false" })

.......Removed HTML

        <div class="col-md-1">
            <span class="glyphicon glyphicon-trash" data-action="removeItem" title="remove" style="cursor:pointer"></span>
        </div>

jQuery JavaScript. (: , , )

, jQuery, HTML. jQuery - IsDeleted true false,

$(document).on('click', '*[data-action="removeItem"]', function(e){
    e.stopPropagation();
    var btn = $(this);
    var row = btn.closest('.row');
    var parent = btn.parent();
    var checkBox = parent.siblings('*[data-is-deleted]');

    var checkBoxVal = checkBox.val();
    if(checkBoxVal == 'False' || checkBox.val() == 'false'){
        checkBox.val('true');
        row.find('input, textarea, select').attr('readonly', 'readonly');
    } else {
        checkBox.val('false');
        row.find('input, textarea, select').attr("readonly", false);
    }
    checkBoxVal = checkBox.val();
});

:

enter image description here

:

foreach (var contact in contacts.Where(s => !s.isDeleted))
{
   // New and Updated Items
}

foreach (var contact in myModel.Where(s => s.isDeleted && s.Id!= 0))
 {              
    // Deleted Items
// You don't have to delete Items where Id == 0, Bcz they are not in the DB.
// Just some Item added to the View and then deleted without Save
  }

: : , jQuery

enter image description here

A: :

[HttpPost]
public ActionResult SaveStudent(Student model){


// Save model items

// Then Save the List of Items like this:

    foreach (var contact in model.myListItems.Where(s => !s.isDeleted))
    {
       // New and Updated Items
    }

    foreach (var contact in model.myListItems.Where(s => s.isDeleted && s.Id!= 0))
     {              
        // Deleted Items
    // You don't have to delete Items where Id == 0, Bcz they are not in the DB.
    // Just some Item added to the View and then deleted without Save
      }


}
+4

Source: https://habr.com/ru/post/1584929/


All Articles