-1

How can i iterate foreach without IEnumerable

Repo.cs

public Employee GetEmployee(int id)
        {

            var x = (from n in db.Employee
                     where n.Emp_Id==id
                     select n);
            return x.FirstOrDefault();
        }

Controller

public ActionResult GetEmpById(int id)
{
     var x = ObjRepo.GetEmployee(id);

    return View(x);
}

Index.cshtml

Here I'm gettin Error as The model item passed into the dictionary is of type 'Mvc_Application.Models.Employee', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Mvc_Application.Models.Employee]'.

@model IEnumerable<Mvc_Application.Models.Employee>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
    </tr>
}

</table>
  • You're mixing List and Singleton , in multiple places. Think about what you actually want first. – H H Oct 03 '17 at 11:04
  • 1
    Your returning a single `Employee` to a view which expects a collection of `Employee` –  Oct 03 '17 at 11:04
  • You have a double `return`. The code as shown does not even use the View... – Peter B Oct 03 '17 at 11:05

2 Answers2

0

It's because you are passing single object to your view. and in view you are accepting IEnumerable of Employee

change in view

@model Mvc_Application.Models.Employee
@*  your code *@
Amit Kumar
  • 5,888
  • 11
  • 47
  • 85
  • plz review my code i just updated –  Oct 03 '17 at 11:08
  • @MDmohi : Please update code in view `.cshtml` file as I suggested. It will work – Amit Kumar Oct 03 '17 at 11:09
  • Error as Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'Mvc_Application.Models.Employee' because 'Mvc_Application.Models.Employee' does not contain a public definition for 'GetEnumerator' –  Oct 03 '17 at 11:11
  • Why you are using for loop. as it wil have only one email. so just use `@Html.DisplayNameFor(model => model.Email)` and remove your `foreach loop` – Amit Kumar Oct 03 '17 at 11:13
  • I have soo many columns Knowly i remove all othe colums –  Oct 03 '17 at 11:15
  • @MDmohi : Than you need to write similar to `@Html.DisplayNameFor(model => model.Email)` for each column. – Amit Kumar Oct 03 '17 at 11:17
0

If this page is intended to show data from a single employee, then, it's model should be @model Mvc_Application.Models.Employee.

Oscar
  • 13,594
  • 8
  • 47
  • 75