返回列表查看 [英] Return List To View
本文介绍了返回列表查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每次我遍历视图包时都会出现此错误
Every Time I loop through the viewbag it gives this error
对象"不包含名称"的定义
object' does not contain a definition for 'Name'
这是我的动作
public ActionResult AssignTask()
{
var List = db.Employees.Select(x => new
{
id = x.id,
Name = x.Name
}).ToList();
ViewBag.Emp_data = List;
return View();
}
这是我的看法
推荐答案
此代码返回List<anonymous>
var List = db.Employees.Select(x => new
{
id = x.id,
Name = x.Name
}).ToList();
所以这就是为什么您无法在视图的foreach
循环中访问Name
属性的原因.
so that's why you can't access Name
property in the foreach
loop in your view.
我建议使用强类型的ViewModel类来保存数据并避免使用ViewBag. ViewModel应该位于Models文件夹中,如下所示
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);
}
并在您看来
@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>
这篇关于返回列表查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文