通过View(object)传递模型数据
- 支持所有c#类型
- 在视图中使用
Model
来获取属性,此时的Model
为动态类型
控制器:
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[Controller]
public class Test : Controller
{
public IActionResult Index()
{
var userModel = new UserModel() {
Username = "test",
Truename = "张三",
TelePhone = "1234565"
};
return View(userModel);
}
}
public class UserModel
{
public string Username { set; get; }
public string Truename { set; get; }
public string TelePhone { set; get; }
}
}
视图:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table>
<tr>
<td>用户名</td>
<td>@Model.Username</td>
</tr>
<tr>
<td>真实姓名</td>
<td>@Model.Truename</td>
</tr>
<tr>
<td>电话</td>
<td>@Model.TelePhone</td>
</tr>
</table>
</body>
</html>
强类型视图
- 强类型Model是一个设计时就能确定具体的数据类型,而不是运行时确定
- 强类型Model能提供设计时的智能提示
- 强类型Model能方便数据绑定及数据验证
- 可以使用
[DisplayAttribute]
来指定类的字段在视图中显示的属性值
控制器:
using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel;
namespace WebApplication1.Controllers
{
[Controller]
public class Test : Controller
{
public IActionResult Index()
{
var userModel = new UserModel() {
Username = "test",
Truename = "张三",
TelePhone = "1234565"
};
return View(userModel);
}
}
public class UserModel
{
[DisplayName("用户名")]
public string Username { set; get; }
[DisplayName("真实姓名")]
public string Truename { set; get; }
[DisplayName("电话")]
public string TelePhone { set; get; }
}
}
视图(在
cshtml
文件上加上@model
即可转化为强类型视图):
@model WebApplication1.Controllers.UserModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table>
<tr>
<td>@Html.LabelFor(m => m.Username)</td>
<td>@Html.TextBoxFor(m => m.Username)</td>
</tr>
<tr>
<td>@Html.LabelFor(m => m.Truename)</td>
<td>@Html.TextBoxFor(m => m.Truename)</td>
</tr>
<tr>
<td>@Html.LabelFor(m => m.TelePhone)</td>
<td>@Html.TextBoxFor(m => m.TelePhone)</td>
</tr>
</table>
</body>
</html>