0

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>
}

1 Answer 1

3

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>
}
Sign up to request clarification or add additional context in comments.

1 Comment

@shindvii please mark the post as answer, if it solved your issue. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.