views:

36

answers:

2

Ok I have a menu system with a menu (Dynamicly Generated from a datavbase field) I want to include this menu system on several views - All of which use differant controllers and models.

<ul>
      <li><a href="#">All</a></li>
          <%
                    foreach (var curCat in Model.CategoryList)
                    {
                %>
                        <li><a href="/messagecentre/category/<%=curCat.CategoryID.ToString() %>"><%= Html.Encode(curCat.Category1)%></a></li>               
                <% 
                   } 
                %>
  </ul>

Whast the best way to achieve this? Do i need to just pass the Categories model with every other model so that I can do the RenderPartial("Name",Model) synatx?

A: 

There are two different ways to accomplish this. You can include the Categories in every model or you can store the Categories in the ViewDataDictionary and retrieve them from there. Normally, I would want to extend the model with data so that I can use it in a strongly-typed way, but in this case -- since the data is ubiquitous -- I would probably go with ViewData and use a base controller to populate it (likely in OnActionExecuted) so that it is always available. In my partial view I would cast the ViewData item to a strongly-typed object and use it from there.

The reason I would do this is to keep my models clean for the actual view, which doesn't need to know about the data for the menu. To me this seems like a reasonable exception to the usual route of creating a view-specific model.

<% var categories = ViewData["categories"] as IEnumerable<Category>; %>
<ul>
    <li><a href="#">All</a></li>
        <%
    foreach (var curCat in categories)
    {
%>
        <li><a href="/messagecentre/category/<%=curCat.CategoryID.ToString() %>"><%= Html.Encode(curCat.Category1)%></a></li>               
<% 
   } 
%>
</ul>
tvanfosson
A: 

Third way--check out the MVC Futures on codeplex, specifically the Html.RenderAction method. Then you can create a controller that just ouputs the menu and let it handle it's business. No need to pollute ViewData.

Wyatt Barnett