0
votes

Problem

when i use remove button to remove course.

it will remove from interface(in client side by jquery) but not save course

removed in database(sql server server side) if i click submit button .

when click submit button to save courses in edit view[HTTP POST] it save

success if i adding new courses

Meaning i can save new course but if i remove course i cannot save

image show

course removed not save in sql server database

code

model class i using is

updated

public class EditEmployeeVm
    {
        public int Id { set; get; }
        public string Name { get; set; }
        public List<SelectListItem> Courses { get; set; }
        public int[] CourseIds { set; get; }
        public List<CourseVm> ExistingCourses { set; get; }
    }
    public class CourseVm
    {
        public int Id { set; get; }
        public string Name { set; get; }
    }
}

updated edit view[HTTP GET] public ActionResult Edit(int id) {

            var vm = new EditEmployeeVm { Id = id };
            var emp = db.Employees.FirstOrDefault(f => f.Id == id);
            vm.Name = emp.Name;
            vm.ExistingCourses = db.EmployeeCourses
                                    .Where(g => g.EmployeeId == id)
                                    .Select(f => new CourseVm
                                    {
                                        Id = f.Id,
                                        Name = f.Course.CourseName
                                    }).ToList();

            vm.CourseIds = vm.ExistingCourses.Select(g => g.Id).ToArray();
            vm.Courses = db.Courses.Select(f => new SelectListItem
            {
                Value = f.Id.ToString(),
                Text = f.CourseName
            }).ToList();

            return View(vm);
        }

in edit view get it show code for remove course by jquery

@model WebCourse.Models.EditEmployeeVm



    <script>
        $(function () {
            $(document).on("click", ".remove", function (e) {
                e.preventDefault();
                $(this).closest(".course-item").remove();
            });
            $('#AvailableCourses').change(function () {
                var val = $(this).val();
                var text = $("#AvailableCourses option:selected").text();
                var existingCourses = $("input[name='CourseIds']")
                    .map(function () { return this.value; }).get();

                if (existingCourses.indexOf(val) === -1) {
                    // Not exist. Add new
                    var newItem = $("<div/>").addClass("course-item")
              .append(text + ' <a href="#" class="remove" data-id="' + val + '">Remove </a>');
                    newItem.append('<input type="text" name="CourseIds" value="' + val + '" />');

                    $("#items").append(newItem);
                }
            });
        });
        </script>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {

            @Html.HiddenFor(g => g.Id)
            @Html.DropDownList("AvailableCourses", Model.Courses, "Select")
            <div id="items"></div>
            foreach (var c in Model.ExistingCourses)
            {
                <div class="course-item">
                    @c.Name <a href="#" class="remove" data-id="@c.Id">Remove </a>
                    <input type="text" name="CourseIds" value="@c.Id" />
                </div>
            }

        }
    </div>
</body>
</html>
in edit view httppost that update data in employeecourse table
 [HttpPost]
        public ActionResult Edit(EditEmployeeVm model)

        {
            var emp = db.Employees.FirstOrDefault(f => f.Id == model.Id);

            foreach (var couseid in model.CourseIds)
            {
                db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });
                db.SaveChanges();

            }

            return View();
        }

update

i need really to replace my code jquery by usine slice function java script to remove index actually

update

i do as below in code

 var existingCourseIds = db.EmployeeCourses.Where(g => g.EmployeeId == model.Id && g.CourseId!=null)
                             .Select(f => f.CourseId.Value).ToList();
            var removedCourseIds = existingCourseIds.Except(model.CourseIds);
            //Now loop through these and delete it from db
            foreach (var removedCourseId in removedCourseIds)
            {
                db.EmployeeCourses.Remove(db.EmployeeCourses.Find(removedCourseId));
                db.SaveChanges();
            }

it give me null exception in the line found inside foreach

error exception value can not null \r\n parameter name entity

link of problem details found in comments below

1

1 Answers

0
votes

The CourseIds property in your view model will have the ids of the courses user selected (after removing or adding). Now in your HttpPost action method, you need to compare it with the existing data (EmployeeCourses for that employee) and find what course id value does not present in the CourseIds property. That will be the Id user must have removed in the UI. Once you have the Id, you can remove it from the db.

You can use the LINQ Except method to find out the difference between the 2 lists.

[HttpPost]
public ActionResult Add(EditEmployeeVm model)
{
    var existingCourseIds = db.EmployeeCourses.Where(g => g.EmployeeId == model.Id)
                              .Select(f=>f.CategoryId).ToList();
    var removedCourseIds = existingCourseIds.Except(model.CourseIds);
    //Now loop through these and delete it from db
    foreach (var removedCourseId in removedCourseIds)
    {
       // TO DO : remove from db
    }
    // Your other save part goes here
    return RedirectToAction("Add");
}