CrazyDart
CrazyDart

Reputation: 3801

Should a model contain all of the data required to build the view?

Lets say I have a site that has a Layout with navigation. This navigation is built each time a page is requested based on options the user has chosen. This navigation does not really have anything to do with the particular view being presented except that it is required for the Layout. The question is, should this be put in the ViewData or should the Model be required to inherit a NavigationModel?

ViewBag.NavItems = navItems;

or

public abstract class NavigationModel
{
    public List<NavItem> NavItems { get; set;}
}

public class HomeModel : NavigationModel
{
}

Upvotes: 1

Views: 257

Answers (2)

Russ Cam
Russ Cam

Reputation: 125488

This sounds like an ideal case to use Html.RenderAction inside of the view to render the navigation. This would call an action on a NavigationController that would be responsible for rendering the menu directly into the view.

Some MVC purists feel that Html.RenderAction breaks true MVC architecture; I see it as a way of delegating responsibility to render certain parts of the view that are not the primary responsibility of the "main" view that you're rendering.

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Should a model contain all of the data required to build the view?

Absolutely and definitely YES.

The question is, should this be put in the ViewData

Absolutely and definitely NO.

You also have the possibility of using Html.Action and Html.RenderAction if this navigation widget could be considered as fully independent part of your site.

Upvotes: 2

Related Questions