Passing a simple IEnumerable to view and using for

2019-07-23 19:19发布

问题:

I have a simple List of Customer model class which I am passing to my view. I want to iterate through the customer class but my view is telling me to bugger off by returning a blank screen. Please tell me what is wrong here?

Model Class:

 public class Customer
    {
        public string CustomerName { get; set; }
        public int Age { get; set; }
    }

Home Controller:

public ActionResult Index()
        {
            List<Customer> customers = new List<Customer>();
            Customer customer = new Customer() { FullName = "MrA" ,Age=25};
            Customer customer2 = new Customer() { FullName = "MrB", Age = 125 };
            return View(customers);
        }

View HTML file

@model IEnumerable<ASPMVC_Database.Models.Customer>
/...some unrelated code

  @foreach( var item in Model)
        {
            @item.FullName <br/>               

        }

This simple code above gives me nothing. Just a white screen. What am I missing out here?

Thank you

回答1:

You never add the new customers to customers, you simple instantiate them. Try the following instead:

public ActionResult Index()
{
    List<Customer> customers = new List<Customer>();
    customers.Add(new Customer { FullName = "MrA", Age = 25});
    customers.Add(new Customer { FullName = "MrB", Age = 125 });
    return View(customers);
}