MVC-强类型
一般的控制器向页面传递对象:
1.需要先把值赋予ViewData或ViewBag,通过它们来把值传递到访问的界面
2.在页面视图中取值往往需要数据转换
3.要直接使用传递的值较麻烦
为解决以上问题,我们学习引入强类型的使用
新建类:
public class User{
public int ID {get;set;}
public string Name{get;set;}
public int Age{get;set;}
public string Photo{get;set;}
}
- 方法一,用ViewData.Model
在控制器:
public ActionResult Index()
{
User u =new User(){
Id=-1,Name="tom",Age=23,Phto="1.png"
}
ViewData.Model=u;
}
在视图页面里(单个对象):
@model 项目名称.Model.User
<html>
<head>
<title></title>
</head>
<body>
<p>编号:@Model.Id</p>
<p>姓名:@Model.Name</p>
<p>年纪:@Model.Age</p>
<p>照片:@Model.Photo</p>
</body>
</html>
在视图页面里(集合):
@model List<项目名称.Models.类>
<html>
<head>
<title></title>
</head>
<body>
<table>
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>照片</th>
</tr>
</thead>
<tbody>
@foreach(var item in Model)
{
<tr>
<td>@item.ID</td>
<td>@item.Name</td>
<td>@item.Age</td>
<td>@item.Photo</td>
</tr>
}
</tbody>
</table>
</body>
</html>
- 方法二,用Return View()
在控制器:
return View("index",db.User.ToList())//用EF模型传值
或者
return View(u)//User u = new User()
return View("index",u)//User u = new User()