The more I use ASP.NET MVC, the more I like it. However, when displaying model data on the main pages, there are several ways to do this. I am not sure about the best solution.
My example would be a commerce site on which I want to list the categories of products on each page, as well as show the status of the visitors basket.
In asp.net web forms, I usually do this with custom controls, each of which performs its own data binding to obtain the required data.
In MVC, all data must be transmitted by the controller.
Thus, with regard to categories, the simplest solution would seem to be to convey this in the data representation in the controller action:
ViewData["Categories"] = _service.GetCategories();
However, doing this for each action is not very DRY, so follow this article. I created a basic controller that adds the required data to my ViewData:
public class AppController : Controller { IAppService _service; public AppController() { } public AppController(IAppService appService) { _service = appService; SetSiteData(); } private void SetSiteData() { ViewData["Categories"] = _service.GetCategories(); } }
Then I created an extension for ViewMasterPage:
public static void RenderCategoryList(this ViewMasterPage pg) { pg.Html.RenderPartial("CategoryList", pg.ViewData["Categories"]); }
And in my MasterPage:
<div> <%this.RenderCategoryList(); %> </div>
This seems like a pretty clean approach. However, this is the best way, as I also saw suggestions for creating a ViewModel for your MasterPage. I could see that perhaps as your ViewModel data grows this might be the best solution.
Regarding the status of the cart, I suppose I would do something similar, but I'm not sure if RenderAction would be more appropriate ( When to use RenderAction vs RenderPartial with ASP.NET MVC ). Thanks Ben