MVC-强类型

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;}
}
  1. 方法一,用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>
  1. 方法二,用Return View()
在控制器:
return View("index",db.User.ToList())//用EF模型传值
或者
return View(u)//User u = new User()
return View("index",u)//User u = new User()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值