
in this image above explain what i need
in the following diagarm i have 3 tables Course Employee EmployeeCourse how to save exist courses in edit post and save data In code below i can get data in edit view get but
i cannot update and save data in database in EmployeeCourse table with existing courses
- update your edit view model to have a collection of CourseVm
- public class EditEmployeeVm
- {
- public int Id { set; get; }
- public string Name { get; set; }
- public List
Courses { get; set; } - public int[] CourseIds { set; get; }
- public List
ExistingCourses { set; get; } - }
- public class CourseVm
- {
- public int Id { set; get; }
- public string Name { set; get; }
- }
- Now in your Edit GET action, populate the ExistingCourse collection.
- 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.CourseId,
- Name = f.Course.Name}).ToList();
- vm.CourseIds = vm.ExistingCourses.Select(g => g.Id).ToArray();
- vm.Courses = db.Courses.Select(f => new SelectListItem {Value = f.Id.ToString(),
- Text = f.Name}).ToList();
- return View(vm);
- }
- I loop through the ExistingCourses collection and display it.
- @model EditEmployeeVm
- @using (Html.BeginForm())
- {
- @Html.HiddenFor(g=>g.Id)
- @Html.LabelFor(f=>f.Name)
- @Html.DropDownList("AvailableCourses" ,Model.Courses,"Select")
Existing courses
- "items">
- foreach (var c in Model.ExistingCourses)
- {
- class="course-item">
- @c.Name "#" class="remove" data-id="@c.Id">Remove
- "text" name="CourseIds" value="@c.Id" />
- }
- "submit"/>
- }
- the view to handle the remove and add of a course.
- @section scripts
- {
- }
- So when you submit the form, The CourseIds property will have the course ids (as an array).
- [HttpPost]
- public ActionResult Edit(EditEmployeeVm model)
- {
- // WHAT CODE I WRITE HERE TO CHECK EXISTING COURSES AND SAVE DATA
- }
Delpin Susai RajPosted Sep 1, 2016, 1:32 PM