kamen
kamen

Reputation: 1

Error: foreach statement cannot operate on variables of type '' because '' does not contain a public definition for 'GetEnumerator'

I want to render data to view from the model which consists of list.

Transaction Model:

public class Transaction
{
    public int AccountId { get; set; }
    public string AccountName { get; set; }
    public string Type { get; set; }
    public DateTime Date { get; set; }
    public int Amount { get; set; }
}

TransactionViewModel:

public class TransactionViewModel
{
    public List<Transaction> Transactions { get; set; }
}

Controller:

public IActionResult Index()
{
   // var dataset = new DataSet();
    using var connection = new NpgsqlConnection(connString);
    connection.Open();

    /* getting account name, type, date, amount from transaction and account table*/
    var sql = @"SELECT *
                    FROM account as a
                         INNER JOIN transaction AS t
                         ON a.account_id = t.account_id";

    using var sqlCommand = new NpgsqlCommand(sql, connection);
    NpgsqlDataReader reader = sqlCommand.ExecuteReader();
    List<Transaction> transaction_Lists = new List<Transaction>();

    if (reader.HasRows)

    {

        while (reader.Read())

        {

            transaction_Lists.Add(new Transaction

            {

                AccountId = Convert.ToInt32(reader["account_id"]),

                AccountName = Convert.ToString(reader["account_name"]),

                Type = Convert.ToString(reader["type"]),

                Amount = Convert.ToInt32(reader["amount"]),


            });

        }

    }

    return View(transaction_Lists);
}

View:

@using System.Data;
@model MyViewModel;

            @foreach(var item in Model)
            {
                <tr>
                    <td>@Model.AccountName</td>
                </tr>
            }

In the view I am getting an error:

foreach statement cannot operate on variables of type '' because '' does not contain a public definition for 'GetEnumerator'"

Why I cannot loop through this?

Upvotes: 0

Views: 1568

Answers (1)

Yong Shun
Yong Shun

Reputation: 51450

From your Index(), you are trying to return View Model as List<Transaction> type.

Change your View as below:

@model List<Transaction>

@foreach(var item in Model)
{
    <tr>
        <td>@item.AccountName</td>
    </tr>
}

Sample MVC (List<Transaction> model)


Or if you want to return the View Model as TransactionViewModel type.

Controller

public IActionResult Index()
{
   ...

    var model = new TransactionViewModel();
    model.Transactions = transaction_Lists;
            
    return View(model);
}

View

@model TransactionViewModel

@foreach(var item in Model.Transactions)
{
    <tr>
        <td>@item.AccountName</td>
    </tr>
}

Sample MVC (TransactionViewModel model)

Upvotes: 1

Related Questions