I have a controller that serves multiple pages. Each page has the following code:
public class SchoolController : Controller
{
private UnitOfWork _unitOfWork = new UnitOfWork();
public ActionResult Details()
{
var viewModel = new RegistryViewModel();
School schoolBeingAccessed = _unitOfWork.SchoolRepository.GetLoggedinSchool();
if (!schoolBeingAccessed.IsActive())
{
return RedirectToAction("NotActive");
}
if (!schoolBeingAccessed.IsExpired())
{
return RedirectToAction("Expired");
}
.....
}
How can I avoid duplicating this code? I can put this code in a function, but then I need to remember about calling the function from each action in the controller.
Normally I would use something like Html.Action ("CheckSchoolStatus") on the _Layout page, however I cannot do this because I am redirecting and you cannot redirect it from a child action.
Is it possible to call this code from the layout page? Or should I use a base controller? How does it work if each view has its own ViewModel?