方式一----------------------------------------------
控制器Index操作中
List<SampleMVC.Models.Person> objList = new List<SampleMVC.Models.Person>();
for (int i = 0; i < 10; i++)
{
objList.Add(new SampleMVC.Models.Person { Name = "张三" + i });
}
ViewBag.Obj = objList;
return View();
Index.cshtml中
@foreach (dynamic item in ViewBag.Obj)
{
@item.Name<br/>
}
----------------------------------------------------------------------------------
方式二-********************************************
控制器Index操作中
List<SampleMVC.Models.Person> objList = new List<SampleMVC.Models.Person>();
for (int i = 0; i < 10; i++)
{
objList.Add(new SampleMVC.Models.Person { Name = "张三" + i });
}
return View(objList);
Index.cshtml
必须将对象转换为IEnumerable对象才能迭代
@model IEnumerable<SampleMVC.Models.Person>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@foreach (SampleMVC.Models.Person item in Model)
{
@item.Name<br/>进行输出人名操作
}
</div>
</body>
</html>
@using SampleMVC.Models//如果不想输入类型完全限定名的话可以引用,可以把常用的引用放入Views中web.config中例如:<add namespace="SampleMVC" />
@model IEnumerable<Person>