I have a dashboard to manage a learning center system. There are scenarios like admin create learning center and define a classroom in it and then assign some courses in it and assign students to those courses and assign a teacher for each courses.
In order to achieve this, I have to create lot of dropdownlists such as for creating a course you have to select first a learning center then an appropriate classroom.
Below is the code for the dropdownlists in assigning a student into a course:
//Retrieve all learning centers
studentAssignmentViewModel.LearningCenters = _learningCenterService.LearningCenters.ToList();
studentAssignmentViewModel.StudentSelectListItem = studentAssignmentViewModel.LearningCenters
.Where(y => y.Status != Status.Removed).OrderBy(x => x.Name)
.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
//Retrieve All Students
studentAssignmentViewModel.Students = _studentAssignmentService.Students.ToList();
studentAssignmentViewModel.StudentSelectListItem = studentAssignmentViewModel.Students
.Where(y => y.Status != Status.Removed).OrderBy(x => x.Name)
.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
//If the user is not admin, it retrieves the courses belong to the teacher otherwise all courses
var userId = _dashboardUserAuthenticationService.AuthenticatedDashboardUser.Id;
var userRole = _dashboardUserService.Get(userId).UserRole;
if (userRole != "1")
{
studentAssignmentViewModel.Courses = _studentAssignmentService.Courses.ToList();
studentAssignmentViewModel.CourseSelectListItem = studentAssignmentViewModel.Courses
.Where(t => (t.Status != Status.Removed) && t.TeacherId == userId).OrderBy(x => x.Name)
.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
}
else
{
studentAssignmentViewModel.Courses = _studentAssignmentService.Courses.ToList();
studentAssignmentViewModel.CourseSelectListItem = studentAssignmentViewModel.Courses
.Where(t => (t.Status != Status.Removed)).OrderBy(x => x.Name)
.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
}
And I am repeating those similar code pieces in edit and create actions in mvc for all scenarios. So I don't know if there is enough information to make a statement but what would be your suggestions for such cases, what would be the best practice to get rid of those ugly code pieces? Since situations vary, turning them into classes would lead me into so many specific classes which cannot be used for any other situation.