1.Model文件,添加Student类
public class Student
{
public int Id{get;set;}
public string FirstName{get;set;}
public string LastName{get;set;}
public DateTime BirthDate{get;set;}
public Gender Gender{get;set}
}
public enum Gender
{
女 = 0,
男 =1,
其他 = 2
}
2.Services文件夹 添加泛型接口IRepository,及继承该接口的InMemroyRepository类
public interface IRepository<T> where T:class
{
IEnumerable<T> GetAll();
T GetId(int Id);
T Add(T newModel);
}
public class InMermoryRepository:IRepository<Student>
{
private List<Student> _students;
public InMermoryRepository()
{
-_students = new List<Student>
{
new Student
{
Id = 1,
FirstName = "Nick",
LastName = "Carter",
BirthDate = new DateTime(1980,1,3)
},
new Student
{
Id = 2,
FirstName = "Jack",
LastName = "Harte",
BirthDate = new DateTime(1984,1,3)
},
new Student
{
Id = 3,
FirstName = "LiLy",
LastName = "Lenda",
BirthDate = new DateTime(1987,1,3)
},
};
}
public IEnumerable<Student> GetAll()
{
return _students;
}
public Student GetById(int id)
{
return _students.FirstorDefault(x => x.Id == id);
}
public Student Add(Student newModel)
{
int maxId = _students.Max(x => x.Id);
newModel.Id = maxId+1;
_students.Add(newModel);
return newModel;
}
}
3.Data文件夹里,添加DataContext类
public class DataContext:DbContext
{
public DataContext(DbContextOptions<Student> options)
:base(options)
{}
public DbSet<Student> Students {get;set;}
}
4.Startup类 及 appsettings.json文件
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(_configuration.GetConnectionString("DefaultConnectiong")));
services.AddSingleton<IRepository<Student>,InMemoryRepositoy>();
}
public void Configure(IApplicationBuilder app, IWebHostEnviroment env)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name:"default",
pattern:"{controller = Home}/{action = Index}/{id?}")
})
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectingStrings": {
"DefaultConnecting": "Data Source=DESKTOP-TCEQP8C\\SQLEXPRESS;Initial Catalog=Tutorial;Integrated Security=True"
}
}
5.Controller文件夹里添加 HomeController类
public class HomeController:Controller
{
private readonly IRepository<Student> _repository;
public HomeController(IRepository<Student> repository)
{
_repository = repository;
}
public IActionResult Index()
{
var list = _repository.GetAll();
var vms = list.Select(x => new StudentViewModel
{
Id = x.Id,
Name = $"{x.FirstName}{x.LastName}",
Age = DateTime.Now.Subtract(x.BirthDate).Days/365
});
var vm = new HomeIndexView
{
students = vms
};
return View(vm);
}
}
Index视图
@using WebApplication1.Model
@model WebApplication1.ViewModels.HomeIndexViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Hello From Index.cshtml</title>
</head>
<body>
<h1>Students</h1>
<ul>
@foreach(var s in students)
{
<li>@s.Name @s.Age
<a asp-aciton = "Detail" asp-route-id = "s.Id">明细Tag</a>
</li>
}
</ul>
<div>
<a asp-aciton="Create">添加一个学生</a>
</div>
</body>
</html>
Detail
public IActionResult Detail(int id)
{
var student = _repository.GetById(id);
if(student == null)
{
return RedirectToAction(nameof(Index));
}
return View(student);
}
对应视图 注意引用的model
@model WebApplication1.Model.Student
<!DOCTYPE html>
<html>
<head>
<title>Detail</title>
</head>
<body>
<div>
<h1>学生信息</h1>
<h2>ID:@Model.Id</h2>
<div>
姓名:@Model.FirstName @Model.LastName
</div>
<div>
性别:@Model.Gender
</div>
<div>
出生日期:@Model.BirthDate.ToString("yyy-MM-dd")
</div>
<div>
<a asp-action ="Index">返回到Home</a>
</div>
</div>
</body>
</html>
Create 要验证
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(StudentCreateViewModel student)
{
if(ModelState.IsValid)
{
var newStudent = new Student
{
FirstName = student.FirstName,
LastName = student.LastName,
BirthDate = student.BirthDate,
Gender = student.Gender
};
var newModel = _repository.Add(newStudent);
return RedirectToAction(nameof(Detail), new { id = newModel.Id });
}
else
{
return View();
}
对应的视图 →→ 提交表单
@using WebApplication1.Model
@using WebApplication1.ViewModles
@model StudentCreateViewModel
<h1>创建学生</h1>
<form method="post">
<div>
<label asp-for="FirstName"></label>
<input asp-for="FirstName" /></input>
<span asp-validation-for="FirstName"></span>
</div>
<div>
<label asp-for="LastName"></label>
<input asp-for="LastName" /></input>
<span asp-validation-for="LastName"></span>
</div>
<div>
<label asp-for="BirthDate"></label>
<input asp-for="BirthDate" type="date" /><input/>
<span asp-validation-for="BirthDate"></span>
</div>
<div>
<label asp-for="Gender"></label>
<select asp-for="Gender" asp-items="Html.GetEnumSelectList<Gender>()">
</select>
<span asp-validation-for="Gender"></span>
</div>
<div asp-validation-summary="All"></div>
<button type="submit" name="save">保存</button>
</form>
6.ViewModels文件夹里,添加3个类
public class StudentViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class HomeIndexViewModel
{
public IEnumerable<StudentViewModel> students { get; set; }
}
public class StudentCreateViewModel
{
[Required, Display(Name = "名")]
public string FirstName { get; set; }
[Required, Display(Name = "姓"), MaxLength(10)]
public string LastName { get; set; }
[Display(Name = "出生日期")]
public DateTime BirthDate { get; set; }
[Display(Name = "性别")]
public Gender Gender { get; set; }
}