C# – In MVC where do you put action methods for views in the shared directory

ccode-organizationdesignmvcnet

I have a website built using a MVC.NET framework with C# that uses some shared views and partial views. In order to display the views properly there is a bit of code that must reside in the controller. Currently I have that logic duplicated between controllers.

An example would be an view that takes in an error id and then pulls down the record from the database and formats the view differently based on the error type. There is a small amount of work that needs to be done to the data in the controller before it can be displayed.

If the view is in the Shared directory where would the controller for it go? Or, is it better design to create a new controller just for it?

I am trying to choose a design that will prevent the "controller creep" that we had in a prior project.

Update: I am currently learning about MVC using Razor and learned about the HTML.Action extension method. If I were going to go back and rewrite this project I would put the method into a "Shared" controller and use HTML.Action to format the data to display it on what ever screen I needed it.

Best Answer

Try to change your viewpoint when you're thinking about this problem. A view doesn't have an action. An action returns a reference to a view. Multiple actions may return references to the same view, or actions may not return a response which isn't related to a view. That's the relevant part of an MVC pattern.

In MVC for ASP.NET, using the default ViewEngine, if an action returns a reference to a view (using return View("ViewName")) then the framework searches first in a folder named after the Controller and then in a folder named "Shared", both in the application's View folder.

So the question "If the view is in the Shared directory where would the controller for it go?" doesn't really make sense. What you should consider is that a view is put into the Shared directory so that it can be accessed by multiple controllers.