数据(模型)绑定
前言:在我以前的文章中谈过.NET CORE 中的模型绑定,文章连接:https://blog.csdn.net/weixin_41372626/article/details/104575685
这篇文章主要从模型角度去说明如何将前端传来的数据绑定到控制器的模型上去构建该数据库实体,这里从更直接从方法的角度去解读,算是对前面文章的补充与扩展。
框架提供了一种默认的数据绑定方式,可以把用户请求的数据绑定到方法的参数上。比如用得最多可能就是通过表单传递数据、查询字符串传递参数。
如果同一个数据在多个数据源里都出现了,(比如同时出现在查询字符串?username=zhangsan、Form表单<input type=”text” username=”lisi” />中,框架会采用默认的优先级别获取数据),但是我又想取特定数据源的数据,怎么办?
需要打上特性:打在方法参数前面 。.NET framewrok下的MVC默认不支持这些特性的,这是.NET CORE 的功能
特性 | 数据源 |
FromHeaderAttribute | Headers(标头) |
FromRouteAttribute | 路由数据 |
FromBodyAttribute | 请求体 |
FromFormAttribute | 表单数据 |
FromQueryAttribute | 查询字符串 |
FromServicesAttribute | 服务注册 |
例子:
控制器
[Controller]
public class Test : Controller
{
public IActionResult SayHello()
{
return View();
}
public IActionResult ProcSayHello(string username)
{
return Content("hello" + username);
}
}
这里后端username既可以来自于查询字符串的username,又可以来自于表单的username,这是默认情况下后端username会接收到来自于From表单中输入的。
前端视图
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SayHello</title>
</head>
<body>
<form method="post" action="/Test/ProcSayHello?username=zhsan">
姓名<input type="text" value="" name="username" /> <input type="submit" value="提交" />
</form>
</body>
</html>
现在需要改为来自于查询字符串的。只需要在控制器的Action方法中加上一个特性。
public IActionResult ProcSayHello([FromQuery] string username)
{
return Content("hello" + username);
}