Is it a good idea to share views between different controllers (using the Views/Shared folder)? I am creating my first MVC application and it requires some pieces of data that are similar to each other. They "explain" different things (and will therefore be stored in different tables) but they each have an Id, Name and Status. I can therefore use different controllers which then use the same View to display the data in a drop down list, allow the user to select one to edit or add a new one via a text box. Obviously I lose the ability to have strongly typed ViewPage data but besides that, would this be considered a good way to do this or am I better off creating a View for each controller to use?
Personally, if the view is generic enough to be used for multiple scenarios then I would use it as so. DRY!
You can still used a strong typed ViewPage in this scenario if you create your own intermediate class for handling the view data.
Define a custom class for your view page:
public class MyCustomViewData
{
public int Id {get; set;}
public string Name {get; set;}
public int Status {get; set;}
}
from within your page:
<% Html.RenderPartial("MyCustomView", new MyCustomViewData ()
{
Id = ViewData.Model.SomeIdField,
Name = ViewData.Model.SomeNameField,
Status = ViewData.Model.SomeStatusField
});
or from the controller
public ActionResult Foo()
{
// get your model data
return View("MyCustomView", new MyCustomViewData ()
{
Id = model.SomeIdField,
Name = model.SomeNameField,
Status = model.SomeStatusField
});
}
With our project we isolate most of the views to the controllers and don't reuse many of them, but we do use a lot of user controls and partial views so that we don't end up repeating ourselves. This lets us keep everything strongly typed as well, perhaps it might suit your scenario?
If you had a common page format, say a table, then you could create a generic view in the Shared folder. This ViewData would have to contain column information as well as the data, as well as some information about any links.
The details are not difficult, and it would save time if there are a lot of similar pages.