Return List To View

末鹿安然 提交于 2019-12-11 05:29:08

问题


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


回答1:


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>



回答2:


You are using an anonymous type which the view doesn't know about. You should still use your Employee class in your select:

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

By the way, you should use a View Model instead of the viewbag to carry the data.



来源:https://stackoverflow.com/questions/39180931/return-list-to-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!