简体   繁体   中英

How can I render my data in ASP.NET with foreach?

I'm new to ASP.NET and I learning ASP.NET with video from Udemy Here's my code

Customer.cs (Model)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace Vidly.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

CustomersController.cs (Controller)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly.Models;

namespace Vidly.Controllers
{
    public class CustomersController : Controller
    {
        //
        // GET: /Customers/
        public ActionResult Index()
        {
            var customers = new List<Customer>
            {
                new Customer {Name = "Mahdi" },
                new Customer {Name = "Yaser" },
                new Customer {Name = "Zahra" },
                new Customer {Name = "Amir"  },
            };
            return View(customers);
        }
    }
}

Index.cshtml (View)

@model Vidly.Models.Customer
<h3>Customer page</h3>
<table class="table table-striped table-hover table-­‐bordered">

    <thead>
        <tr>
            <th>Customer</th>
        </tr>
    </thead>

    <tbody>
        @foreach (var customer in Model)
        {
            <tr>
                <td><a href="#"> @customer.Name </a></td>
            </tr>
        }
    </tbody>
</table> 

visual studio tells me problem is my @foreach but I don't know how to fix it! Thanks for helping ;)

Change

@model Vidly.Models.Customer

To

@model IEnumerable<Vidly.Models.Customer>

In your index.cshtml , check your model. You have to replace it with :

@model List<Vidly.Models.Customer>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM