1.模板
1.1添加模板
在Views文件夹下添加Shared文件夹,然后添加mvc布局页
_LayoutPage1.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
<h3>Header</h3>
<hr />
@RenderBody()
<hr />
<h3>Footer</h3>
</div>
</body>
</html>
再去控制器Home的View里面添加
image.png
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
<h2>这是Home页的Body</h2>
image.png
1.2 使用RenderSection控制布局
_LayoutPage1.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderSection("nav")
<h3>Header</h3>
<hr />
@RenderBody()
<hr />
<h3>Footer</h3>
@RenderSection("bottom")
</div>
</body>
</html>
Index.cshtml
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
<h2>这是Home页的Body</h2>
@section nav
{
<p>这是导航栏</p>
}
@section bottom
{
这是底部信息栏
}
image.png
2.WebApi
2.1 基于资源的WebApi创建
新版本没有using System.Web.Http; 需要安装包
image.png
打开控制台输入:
Install-Package Microsoft.AspNet.WebApi如有只是版本太低更新:
Update-Package Microsoft.AspNet.WebApi -reinstall
-
创建项目
image.png
-
结构
namespace WebApiTest.Controllers
{
public class UserInfoController : ApiController
{
// GET: api/UserInfo
//查询所有信息
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/UserInfo/5
//查询当个信息根据id
public string Get(int id)
{
return "value";
}
// POST: api/UserInfo
//增加
public void Post([FromBody]string value)
{
}
// PUT: api/UserInfo/5
//修改
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/UserInfo/5
//删除
public void Delete(int id)
{
}
}
}
2.2 WebApi调用
方法一:通过ajax调用
image.png
- 创建一个读写的控制器
UserInfoController.cs
namespace WebApi3.Controllers
{
public class UserInfoController : ApiController
{
// GET: api/UserInfo
public IEnumerable<Students> Get()
{
List<Students> stuList = new List<Students>();
//通过BLL-DAL数据库查询获取数据
stuList.Add(new Students { Id = 1, Name = "fxx" });
stuList.Add(new Students { Id = 2, Name = "gjj" });
stuList.Add(new Students { Id = 3, Name = "hjj" });
return stuList;
}
}
- 创建
Index.html发送ajax请求,不支持跨域
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="Scripts/jquery-3.4.1.min.js"></script>
<script>
$(function () {
LoadList();
});
function LoadList() {
$.ajax({
type: 'get',//请求方式,可以为Get,Post,Put,Delete
data: {},//发送的参数
url: 'http://localhost:4985/api/userinfo',//请求地址
contentType: 'application/json; charset=utf-8',//数据类型
dataType: 'json',
success: function (list) {
var list1 = $('#list');
list1.empty();
$.each(list, function (index, item) {
list1.append('<tr><td>' + item.Id + '</td><td>' + item.Name + '</td></tr>');
});
}
});
}
</script>
</head>
<body>
<table border="1">
<tr>
<th>编号</th>
<th>姓名</th>
</tr>
<tbody id="list">
</tbody>
</table>
</body>
</html>
方法二:通过HttpClient对象
可跨域













网友评论