sikka karma
sikka karma

Reputation: 115

How to print the data of a list or an array using foreach loop in Model view in asp.net MVC

This is my controller class and employee is defined in a separate class,Every property is assigned correctly using intellisense.

    using System.Web.Mvc;
    using MVCDemo.Models;
    using System.Collections.Generic;

    namespace MVCDemo.Controllers
    {
        public class EmployeeController : Controller
        {
            // GET: Employee
            public ActionResult Details()
            {
                List<Employee> empList = new List<Employee>()
                {
                    new Employee {EmployeeID = 44, Name = "sunny",Gender = "Male",City="Bangkutir" },
                    new Employee {EmployeeID = 55, Name = "Lucas",Gender = "Male",City="Delphi" },
                    new Employee {EmployeeID = 66, Name = "Harada",Gender = "Male",City="Japan" },
                    new Employee {EmployeeID = 77, Name = "Jadhaw",Gender = "Male",City="India" },
                };
                return View(empList);
            }
        }
    }

Here is my view created using Scaffolding .But in foreach loop what value should be given at the place of collection.

when putting empList it is giving error empList is not available in this context.

@model MVCDemo.Models.Employee

@{
    ViewBag.Title = "Details";
}

<h2>Details of Employees</h2>
@foreach (var emp in empList)
{
    <p>@emp.Name</p>
}

Upvotes: 0

Views: 2378

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

As you are passing List<MVCDemo.Models.Employee> back to the view,your model should also be defined as List<Employee> in the View.

@model List<MVCDemo.Models.Employee>

Then iterate on the Model as that is holding the instance of model passed via controller action i.e. empList, so Model actually represent now instance of List<MVCDemo.Models.Employee> and you can loop through it now:

@model List<MVCDemo.Models.Employee>

@foreach (var emp in Model)
{
   <p>@emp.Name</p>
}

Upvotes: 3

Related Questions