views:

68

answers:

2

Hey all, Sorry its me again. This time I have a question that I think is fairly general. I am using code that is almost exactly the same over and over again within a controller to set up a viewModel. My question was, is there a way to store this code somewhere within the MVC project, possibly have it return a viewModel, and call it from controllers also within the same project.

I am trying to follow DRY but cant seem to find any resources on this one. Thanks in advance!

+11  A: 

You can create a base controller to do your work, then inherit from in in all your controllers and call the methods you want to reuse.

public abstract class BaseController : Controller
{
    protected BaseController()
    {

    }

    protected void PopulateViewModel()
    {
        //code to populate view model here
    }
}

public class MyController : BaseController
{
    [HttpGet]
    public virtual ActionResult myAction()
    {
        PopulateViewModel();
        //do more stuff
    }
}
Climber104
+1  A: 

I like to have a "Helpers" folder that contains things like this for cross-controller re-used functions.

If it's only used in one controller, I like to put the functions at the bottom of the controller and mark them private so that they can't be actions.

i don't know if either of these are proper, but they keep they code pretty tidy and organized and keep things together nicely.

Patricia
This worked really well. I wasnt aware you could do that with the helpers folder, thanks!
Mark
Inheriting from a base class is more inline with standard OO and DRY principles. Helper files and utility classes tend to be less discoverable from a development perspective so when people come behind you they can't find your functions as easily.
John