views:

33

answers:

2

I am very new to MVC and am looking for the best way to handle access to the Enumerator of the following class when used as the type of a View:

 public class TemplateCollection : IEnumerable<Template>
    {
        private IEnumerable<Template> templates;

        public TemplateCollection()
        {
            LoadTemplates();
        }

        public IEnumerator<Template> GetEnumerator()
        {
            return templates.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return templates.GetEnumerator();
        }
}

My view (more or less):

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TemplateCollection>" %>
<asp:Content  ContentPlaceHolderID="MainContent" runat="server">
           <%foreach(var template in ViewData ??) %>
</asp:Content>

How do I access the Enumerator in my foreach loop? Or do I need to create a container class that exposes my TemplateCollection as a property and access that view ViewDate["TemplateCollection"] ?

Thanks,

+1  A: 

You don't really need to define a new collection type class to use as model. You can simply use:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Template>>" %>

But in both cases you must use the Model property instead of the ViewData property Like this:

<asp:Content  ContentPlaceHolderID="MainContent" runat="server">
           <%foreach(var template in Model) %>
</asp:Content>

Obs. Do not use IEnumerable<TemplateCollection> or It will be the same as IEnumerable<IEnumerable<Template>> and I don't think that this is what you want.

Sir Gallahad
Sir, I think your solution will work but my TemplateCollection may contain other properties that I need access to. I don't want to have to pass only the "Templates" enumerable as a parameter. I agree that might be difficult to discern from my question. +1 but not the answer I was looking for. (It is however the default for the view that is generated by Studio.) Thanks
Andrew Robinson
Also, the purpose of the new collection was to act as a top level container for a number of properties etc.; it wasn't to simple accomplish the passing from controller to view.
Andrew Robinson
No problem. In that case you can simply use ViewPage<TemplateCollection> and access through the Model property or as the class TemplateCollection is derived from IEnumerable<Template> you can use ViewPage<IEnumerable<Template>> and use a cast to cast your custom properties. Like that: ((TemplateCollection)Model).YourCustomProperty.
Sir Gallahad
A: 

Actually pretty simple:

<%foreach (var template in Model) { } %>
Andrew Robinson