-1

I have to retrieve a collection of objects from table using loop. But I got an error that

The model item passed into the dictionary is of type 'ThaniyamBank.Models.Board', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[A.Models.Board]'

Why this error is coming ? How can I solve this error ?Should I need to change my query ?

controller

public ActionResult Board()
{
    var res = db.Boards.Select(t => new
    {
        Id = t.Id,
        Name = t.Name,
        Designation = t.Designation,
        Phone = t.Phone
    }).ToList();
    return View(res);
}

view

@model List<A.Models.Board>

@for (var j = 0; j < Model.Count(); j++)
{
    <tr>
        <td>
            @Html.HiddenFor(m => m[j].Id)
            @Html.HiddenFor(m => m[j].Name)
            @Html.DisplayFor(m => m[j].Designation)
            @Html.DisplayFor(m => m[j].Phone)
        </td>
    </tr>
}

model class

public partial class Board
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Designation { get; set; }
    public string Phone { get; set; }
    public string PhotoUrl { get; set; }
}

I need to get the name , designation, and phone of all the peoples in the Board but i am getting an error that .

How can I fix this error?

How to retrieve a collection of data from table ??

teo van kot
  • 12,350
  • 10
  • 38
  • 70
athira
  • 19
  • 6
  • 1
    That is not the error message that your code generates (its states your sending a single instance of `Board` to the view, but your code is sending a collection of anonymous objects) so either you have not shown the correct code or you have not shown the correct message –  Feb 08 '17 at 10:33
  • But what is the point of this anyway - the controller code just needs to be `var res = db.Boards.ToList(); return View(res);` –  Feb 08 '17 at 10:36

1 Answers1

0

You passing anonymouse object to View but expecting strongly typed class.

Your controller side should be:

public ActionResult Board()
{
    var res = db.Boards
           .Select(t => new A.Models.Board //note this
           {
               Id = t.Id,
               Name = t.Name,
               Designation = t.Designation,
               Phone=t.Phone
           }).ToList();
    return View(res);
}

Or event simplier, if you using DB model on View:

public ActionResult Board()
{
    var res = db.Boards.ToList();
    return View(res);
}
teo van kot
  • 12,350
  • 10
  • 38
  • 70