Skip to content

How to Update exist course id in EmployeeCourse table

ahmed salah

Asked Aug 31, 2016, 2:06 PM EDT1 answer
Share
LinkedInX
 
 
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
    1. update your edit view model to have a collection of CourseVm  
    2. public class EditEmployeeVm  
    3. {  
    4. public int Id { set; get; }  
    5. public string Name { get; set; }  
    6. public List Courses { get; set; }  
    7. public int[] CourseIds { set; get; }  
    8. public List ExistingCourses { set; get; }  
    9. }  
    10.   
    11. public class CourseVm  
    12. {  
    13. public int Id { set; get; }  
    14. public string Name { set; get; }  
    15. }  
    16. Now in your Edit GET action, populate the ExistingCourse collection.  
    17.   
    18. public ActionResult Edit(int id)  
    19. {  
    20. var vm = new EditEmployeeVm { Id=id };  
    21. var emp = db.Employees.FirstOrDefault(f => f.Id == id);  
    22. vm.Name = emp.Name;  
    23. vm.ExistingCourses = db.EmployeeCourses  
    24. .Where(g=>g.EmployeeId==id)  
    25. .Select(f => new CourseVm { Id = f.CourseId,  
    26. Name = f.Course.Name}).ToList();  
    27.   
    28. vm.CourseIds = vm.ExistingCourses.Select(g => g.Id).ToArray();  
    29. vm.Courses = db.Courses.Select(f => new SelectListItem {Value = f.Id.ToString(),   
    30. Text = f.Name}).ToList();  
    31. return View(vm);  
    32. }  
    33. I loop through the ExistingCourses collection and display it.  
    34.   
    35. @model EditEmployeeVm  
    36. @using (Html.BeginForm())  
    37. {  
    38. @Html.HiddenFor(g=>g.Id)  
    39. @Html.LabelFor(f=>f.Name)   
    40. @Html.DropDownList("AvailableCourses" ,Model.Courses,"Select")   
    41. Existing courses
        
    42. "items"
      >
      
  1. foreach (var c in Model.ExistingCourses)  
  2. {  
  3. class
    ="course-item">   
  4. @c.Name "#" class="remove" data-id="@c.Id">Remove    
  5. "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  
  • }  
  • 1 Answer

    Know the answer? Post it. Somebody with the same question will find it here.

    • Delpin Susai Raj
      0
      http://forums.asp.net/t/2102656.aspx?How+to+Update+exist+course+id+in+EmployeeCourse+table+and+save+data+in+edit+view+post
      0