I have a multiple list-group-items inside a list-group and i want to be able re-order using up and down arrows. I want also be able to save this order so when i come back on after refreshing the page the new order is still presesent.
I have managed to use JavaScript to move the html elements up and down using the arrow buttons. I have also added public int OrderNum to the model and the list group is ordered by increasing OrderNum. However i’m struggling to be able to change the orderNUm when the button is pressed
C#
public class Lesson : IModel
{
public override String partitionKey { get => CourseId; }
[Required]
public string CourseId { get; set; }
[Required]
[StringLength(256, ErrorMessage = "Maximum {1} characters")]
public string Title { get; set; }
[Required]
public string Content { get; set; }
public string ImageID { get; set; }
public string ImageURL { get => (ImageID != null) ? Storage.Image.Path(ImageID) : null; }
public int OrderNum { get; set; }
}
HTML
@foreach (var Lesson in Model.Lessons.OrderBy(x => x.OrderNum))
{
<li class="list-group-item">
<a href="@Url.Action("Index","Lesson", new { CourseCategory = Model.Course.Category, CourseID = Model.Course.id, Lesson.id })">@Lesson.OrderNum</a>
@if (AppUser.CurrentUser.Areas.Admin)
{
<a class='up' href='#'><i class="fa-solid fa-arrow-up fa-lg"></i></a> <a class='down' href='#'><i class="fa-solid fa-arrow-down fa-lg"></i></a>
<div class="Edit-Buttons-L">
<div>
<a href="@Url.Action("EditLesson", "Lesson", new { CourseCategory = Model.Course.Category, CourseID = Model.Course.id, Lesson.id })">
<i class="fa-regular fa-pen-to-square fa-lg"></i>
</a>
</div>
<div>
<form action="@Url.Action("DeleteLesson","Lesson", new{CourseCategory = Model.Course.Category, CourseID = Model.Course.id, Lesson.id})" method="post">
<button type="submit" class="fa-regular fa-trash-can fa-lg" value="Delete"></button>
</form>
</div>
</div>
}
</li>
}
JavaScript
window.onload = function () {
var upLink = document.querySelectorAll(".up");
for (var i = 0; i < upLink.length; i++) {
upLink[i].addEventListener('click', function () {
var wrapper = this.parentElement;
if (wrapper.previousElementSibling)
wrapper.parentNode.insertBefore(wrapper, wrapper.previousElementSibling);
});
}
var downLink = document.querySelectorAll(".down");
for (var i = 0; i < downLink.length; i++) {
downLink[i].addEventListener('click', function () {
var wrapper = this.parentElement;
if (wrapper.nextElementSibling)
wrapper.parentNode.insertBefore(wrapper.nextElementSibling, wrapper);
});
}