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) {
$(this).closest('.studentRow').remove();
}
else {
var url = '@Url.Action("action", "controller")';
$.post(url, { ID: id }, function (response) {
if (response) {
$(this).closest('.studentRow').remove();
}
}).fail(function (response) {
});
}
});
</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
{
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();
}
}