Search code examples
c#asp.net-mvcloopsviewbag

Return List To View


Every Time I loop through the viewbag it gives this error

object' does not contain a definition for 'Name'

This My Action

public ActionResult AssignTask() 
{
    var List = db.Employees.Select(x => new 
    { 
        id = x.id, 
        Name = x.Name
    }).ToList();

    ViewBag.Emp_data = List;

    return View();
}

and this is my view enter image description here


Solution

  • This code returns a List<anonymous>

    var List = db.Employees.Select(x => new 
    { 
        id = x.id, 
        Name = x.Name
    }).ToList();
    

    so that's why you can't access Name property in the foreach loop in your view.

    I would suggest using a strongly typed ViewModel class to hold the data and avoiding ViewBag. The ViewModel should be in Models folder and look like below

    public class EmployeeViewModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    

    Change your controller as below

    public ActionResult AssignTask() 
    {
        var model = db.Employees.Select(x => new EmployeeViewModel
        { 
            ID = x.id, 
            Name = x.Name
        }).ToList();
    
        return View(model);
    }
    

    and in your view

    @model List<EmployeeViewModel>
    
    <h2>AssignTask</h2>
    <div class="row">
        <div class="form-group">
            <div style="overflow-y:scroll; overflow-x:hidden; height:400px;">
                @foreach (var item in Model)
                {
                    <div class="col-lg-4 col-md-4">
                        <label>@item.Name</label>
                        <input type="checkbox" class="checkbox" name="SelectEmp" value="@item.ID" />
                    </div>
                }
            </div>
        </div>
    </div>