foreach语句不能对类型''的变量进行操作,因为''不包含'GetEnumerator'的公共定义

Sat*_*ish 2 asp.net-mvc-2

我有类似于此描述的错误:在编译服务此请求所需的资源期间发生错误.请查看以下特定错误详细信息并相应地修改源代码.

Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'EventListing.Models.EventInfo' because 'EventListing.Models.EventInfo' does not contain a public definition for 'GetEnumerator'

Source Error:

Line 106:                </th>
Line 107:            </tr>
Line 108:            <% foreach (var model in Model)
Line 109:               { %>
Line 110:            <tr>
Run Code Online (Sandbox Code Playgroud)

模型

public static List<EventInfo> EventList()
        {
            var list = new List<EventInfo>();
            Dbhelper DbHelper = new Dbhelper();
            DbCommand cmd = DbHelper.GetSqlStringCommond("SELECT * FROM WS_EVENTINFO");
            DbDataReader Datareader = DbHelper.ExecuteReader(cmd);
            while (Datareader.Read())
            {
                EventInfo eventinfo = new EventInfo()
                {
                    EVENT_ID = Convert.ToInt32(Datareader[
Run Code Online (Sandbox Code Playgroud)

查看页面

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<EventListing.Models.EventInfo>" %>
 <% foreach (var model in Model)
               { %>
            <tr>
                <td>
                    <%= Html.ActionLink(Model.TITLE,"Detail", new {id = Model.EVENT_ID})%>
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题,我正在使用MVC2框架.

Sam*_*ich 5

您需要将集合绑定为模型.查看这篇文章了解详情:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

视图

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IList<EventListing.Models.EventInfo>>" %>
Run Code Online (Sandbox Code Playgroud)

调节器

public ActionResult List()
{
   return this.View(EventList());
}
Run Code Online (Sandbox Code Playgroud)

或者使用其他类型的模型并List<EventInfo> Events在其中定义属性.然后按以下方式迭代:

<% foreach (var model in Model.Events)
    { %>
Run Code Online (Sandbox Code Playgroud)

此外,Visual Studio可以为您完成:

在此输入图像描述

在此输入图像描述