This StudentController class is responsible for handling HTTP requests related to student entities in the web application.Let's review its key functionalities
using FreeWebApplication.Models;
using
FreeWebApplication.OtherService;
using
FreeWebApplication.Repository;
using Microsoft.AspNetCore.Mvc;
namespace FreeWebApplication.Controllers {
public class StudentController : Controller
{
private readonly StudentService
_studentService;
public
StudentController(StudentService studentService)
{
_studentService
= studentService;
}
public IActionResult Index(string
sortOrder, string searchString, int pageNumber = 1, int pageSize = 10)
{
var options = new QueryOptions <
StudentModel >
{
PageNumber =
pageNumber,
PageSize =
pageSize
};
switch (sortOrder) {
case "name_desc":
options.OrderBy = b => b.Name;
options.OrderByDirection = "desc";
break;
case "name_asc":
options.OrderBy = b => b.Name;
options.OrderByDirection
= "asc";
break;
case "CreateDate":
options.OrderBy = b => b.CreateDate;
break;
case "CreateDate_desc":
options.OrderBy = b => b.CreateDate;
options.OrderByDirection = "desc";
break;
default:
options.OrderBy = b => b.CreateDate;
break;
}
if (!string.IsNullOrEmpty(searchString))
{
options.Where = s => s.Name.Contains(searchString);
}
var students =
_studentService.GetAllStudents(options);
var viewModel = new PaginationViewModel <
StudentModel >
{
Items =
students,
PageIndex =
pageNumber,
PageSize =
pageSize,
CurrentSort
= sortOrder,
TotalPages =
_studentService.GetTotalPages(options)
};
ViewBag.CurrentFilter
= searchString;
return View(viewModel);
}
public IActionResult Details(int
id)
{
var student =
_studentService.GetStudentById(id);
return View(student);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult
Create(StudentModel student)
{
if (ModelState.IsValid) {
_studentService.AddStudent(student);
return RedirectToAction(nameof(Index));
}
return View(student);
}
public IActionResult Edit(int id)
{
var student = _studentService.GetStudentById(id);
return View(student);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult
Edit(StudentModel student)
{
if (ModelState.IsValid) {
_studentService.UpdateStudent(student);
return RedirectToAction(nameof(Index));
}
return View(student);
}
public IActionResult Delete(int id)
{
_studentService.DeleteStudent(id);
return RedirectToAction(nameof(Index));
}
}
}