using Microsoft.AspNetCore.Mvc;
//Blog项目名 Models中有新建文件需要引用
using Blog.Models;
//Blog项目名
namespace Blog.Controllers;
//BlogsController跟控制器名字取的一样
public class BlogsController : Controller
{
// 返回视图 用于整个页面
public IActionResult Index()
{
return View(Db.Blogs);
}
// 增加页面
public IActionResult Increase()
{
return View();
}
// 编辑页面
public IActionResult Redact()
{
return View();
}
// 删除页面
public IActionResult Delete()
{
return View();
}
}
3. _ViewStart.cshtml中的默认模板页面可改为空(选择)
cs复制代码
@{
Layout = null;
}
4. 在View中
控制器(Controller)名字和视图(View)中的文件名要一模一样
创建文件夹Blogs
创建文件Index.cshtml
5. 在Properties中(选择)
launchSettings.json 中端口可改为5000
6. 在4.中的Index.cshtml中写需要的内容页面
7. 在wwwroot中写css文件(如需css文件的话)
css文件名为base.css
link在Index.cshtml页面中书写
cs复制代码
<link rel="stylesheet" href="~/css/base.css">
8. 在Models中创建Blogs.cs 模型
字段名
Blogs.cs中
cs复制代码
namespace Blog.Models;
public class Blogs
{
public int Id{get;set;}
public string Title{get;set;}=null!;
public string Content{get;set;}=null!;
public string Author{get;set;}=null!;
}
9. 在Models中创Db.cs(模拟数据库创建)
静态字段
Db.cs中
cs复制代码
namespace Blog.Models;
public static class Db
{
// 集合
public static List<Blogs> Blogs{get;set;}
// 构造函数
static Db()
{
Blogs=[];
for (var i = 1; i <=10; i++)
{
var tmp = new Blogs
{
Id=i,
Title=$"永远是朋友{i}",
Content=$"假日风情{i}",
Author="哈哈"
};
Blogs.Add(tmp);
}
}
}
10. 在Index.cshtml中
增删改查需要跳转的页面就改换位a标签
input(button) --》 改换成a标签
asp-action可以跳转到书写的页面
Increase 是在Views下的Blogs中创建的Increase.cshtml
html复制代码
<a asp-action="Increase">增加</a>
11. 在Models中写的Db.cs
记得在控制器BlogsController.cs中返回视图
cs复制代码
public IActionResult Index()
{
return View(Db.Blogs);
}
完整版
1. 在Controllers需要写的文件
BlogsController.cs中
cs复制代码
using Microsoft.AspNetCore.Mvc;
using Blog.Models;
namespace Blog.Controllers;
public class BlogsController : Controller
{
public IActionResult Index()
{
return View(Db.Blogs);
}
public IActionResult Increase()
{
return View();
}
public IActionResult Redact()
{
return View();
}
public IActionResult Delete()
{
return View();
}
}
2. 在Models中需要写的文件
在Blogs.cs文件中
cs复制代码
namespace Blog.Models;
public class Blogs
{
public int Id{get;set;}
public string Title{get;set;}=null!;
public string Content{get;set;}=null!;
public string Author{get;set;}=null!;
}
在Db.cs文件中
cs复制代码
namespace Blog.Models;
public static class Db
{
public static List<Blogs> Blogs{get;set;}
static Db()
{
Blogs=[];
for (var i = 1; i <=10; i++)
{
var tmp = new Blogs
{
Id=i,
Title=$"永远的友谊{i}",
Content=$"开心每一天{i}",
Author="哈哈"
};
Blogs.Add(tmp);
}
}
}