Search code examples
c#asp.net-mvc-3methodsasp.net-mvc-controller

Common method among multiple controllers


I have a common method among multiple controllers, not all. Is correct to put the method in a controller base and all other controllers inherit it?

public class BaseController : Controller
{
    public IEnumerable<SelectListItem> GetStatus()
    {
        IList<SelectListItem> status = new List<SelectListItem>();

        status.Add(new SelectListItem() { Text = "Select", Value = "" });

        Enum.GetValues(typeof(Status)).Cast<Status>().ToList().Select(x => new SelectListItem()
        {
            Text = x.ToString(),
            Value = ((byte)x).ToString()
        }).ToList().ForEach(status.Add);

        return status;
    }
}

public class DownloadController : BaseController
{
    public ActionResult New()
    {
        NewViewModel newViewModel = new NewViewModel();

        newViewModel.Status = GetStatus();

        return View(newViewModel);
    }
}

Solution

  • Based on this line,

    newViewModel.Status = GetStatus();
    

    I would argue that the GetStatuses shouldn't be a method on a controller. Controllers should handle Http requests and return http responses. These responses can be files, views, json, etc... But it looks though as this is not how your using GetStatuses, and that it is not intended to be returned as an Http response. If this is indeed the case, it should go else where.

    My MVC applications always have a service layer that serve up view models. So in my application, this service layer would server up the Statuses.