andleer
andleer

Reputation: 22568

MVC strongly typed View access to GetEnumerator()

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,

Upvotes: 1

Views: 766

Answers (2)

andleer
andleer

Reputation: 22568

Actually pretty simple:

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

Upvotes: 0

Andre Vianna
Andre Vianna

Reputation: 1732

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.

Upvotes: 1

Related Questions