高端企业网站信息株洲市住房和城乡建设局门户网站
文章目录
- 项目地址
 - 一、创建项目结构
 - 1.1 创建程序以及Controller
 - 1.2 创建View
 - 1.3 创建Models层,并且在Edit页面显示
 - 1.4 创建Layou模板页面
 - 1.5 创建静态文件css中间件
 
- 二、Categories的CRUD
 - 2.1 使用静态仓库存储数据
 - 2.2 将Categorie的列表显示在页面中(List)
 - 2.3 创建_ViewImport.cs文件,将有公共引入写入
 - 2.4 创建Edit页面的表单提交 (Update)
 - 2.4.1 给修改字段添加一些验证
 - 2.4.2 使用数据注解Data Annotations
 
- 2.5 添加Add逻辑(Create)
 - 2.5.1 在Controller里添加Add的逻辑
 - 2.5.2 在Index页面添加Add按钮
 
- 2.6 删除逻辑
 - 2.6.1 在Layout页面设置一个Js的异步Section
 
- 2.7 使用Partial View处理重复代码
 - 2.7.1 使用ViewBag传递Controller的名称
 
- 2.7.2 提取公共部分,不同的地方进行判断
 - 2.7.3 删除重复代码,使用partial视图
 
- ViewModel的设计原则
 
项目地址
-  
教程作者:王教员
 -  
教程地址:
 
https://www.bilibili.com/video/BV1Sn4y1o7EV?spm_id_from=333.788.player.switch&vd_source=791e6deaa9c8a56b1f845a0bc1431b71&p=6
 
- 代码仓库地址:
 
https://github.com/CXTV/WebApp
 
- 所用到的框架和插件:
 
.net 8
 
一、创建项目结构
1.1 创建程序以及Controller
- 使用空的.net core程序来制作mvc结构
 
- 创建一个空的.net core程序
 - 在Program.cs的程序入口,注册我们依赖项
 
var builder = WebApplication.CreateBuilder(args);//1.注入服务
builder.Services.AddControllersWithViews();var app = builder.Build();//2.添加中间件
app.UseRouting();//3.添加控制器
app.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");app.Run(); 
- 创建
controllers文件夹,并且添加一个HomeController.cs 
- 当一个url通过匹配后,先回找到对应的controller,然后根据页面的view,找到对应的action; 例如:用户访问了
/Home/Index.html,就回找到下面的方法Index() 
using Microsoft.AspNetCore.Mvc;namespace WebApp.Controllers
{public class HomeController : Controller{public string Index(){return "Hello /Home/index";}}
}
 
- 通过访问
https://localhost:7140/home/index就可以访问到返回的字符串 
1.2 创建View
-  
直接在HomeController里的Index() Action自动添加View,就会得到下面的文件结构,其中Home对应的就是HomeController控制器;
Index.cshtml就是对应的action的视图文件

 -  
将需要编辑的内容放入到视图页面
/Views/Home/Index.cshtml

 
1.3 创建Models层,并且在Edit页面显示
- 创建Models文件夹,并且添加
Category.cs 
namespace WebApp.Models
{public class Category{public int CategoryId { get; set; }public string? Name { get; set; }public string? Description { get; set; }}
}
 
- 在
CategoriesController.cs里添加一个Edit页面,实例化Models里的类,并且传递给View()视图 
public IActionResult Edit(int? id)
{var category = new Category{CategoryId = id.HasValue?id.Value : 0};return View(category);
}
 
- 创建一个Eidt的视图, 将Index页面传递的Id,展示在Edit页面里
 

1.4 创建Layou模板页面
- 在
Views文件夹里Shared文件夹,并且创建_Layout.cshtml 

 2. 添加/View/_ViewStart.cshtml,全局的页面都将使用_Layout.cshtml页面作为模板页
@{Layout = "_Layout";
}
 
- 补充,如果其他页面想用其他的Layout,可以使用
 
Views/
├── _ViewStart.cshtml  // 全局的默认配置
├── Home/
│   ├── Index.cshtml
│   ├── _ViewStart.cshtml  // 只影响 Home 下的视图 
- 其他页面只需要写
@RenderBody()里面的内容即可 
<h3 class="d-block">Categories</h3>
<div class="d-block"><ul><li><a href="/categories/edit/1">Beverage</a></li><li><a href="/categories/edit/2">Meet</a></li></ul>
</div>
 
1.5 创建静态文件css中间件
- 添加
ww 
