Question

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);
    }
}
Was it helpful?

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.

OTHER TIPS

That seems right, you could probably make it static and protected.

I would actually take a different approach. I use some custom HTML Helpers for this, similar to the following:

http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx

That way you can just use:

 <%: Html.EnumDropDownListFor(model => model.EnuProperty) %>

I prefer the answer submitted by Simon which allows you to use the Meta Description attribute to customzie the output for Enum names:

How do you create a dropdownlist from an enum in ASP.NET MVC?

I would favor composition over inheritance and encapsulate the code in another object, then inject the object into the controller. especially in this instance.

and in this case setting up the rendering of the Enum list may even be better suited for a partial controller/view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top