【ASP.NET Core学习】Razor页面
准备工作
- 初始化空的项目(终端输入:dotnet new web -n=Razor)
- Nuget添加Microsoft.EntityFrameworkCore.SqlServer 和 Microsoft.EntityFrameworkCore.Design
- 添加必要服务
ConfigureServices添加Razor支持
public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); }
修改app.UseEndpoints为
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
添加数据库
[Table("Book")] public class Book { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Display(Name = "书名")] [Required(ErrorMessage = "书名不能为空")] [StringLength(50, ErrorMessage = "书名最大长度为50")] public string Name { get; set; } [Display(Name = "单价")] [Column(TypeName = "decimal(18, 2)")] [Range(0.01, 10000, ErrorMessage = "单价范围只能在(0.01 ~ 10000)"), DataType(DataType.Currency)] public decimal UnitPrice { get; set; } [Display(Name = "出版日期")] [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")] public DateTime PublicationDate { get; set; } [Display(Name = "创建时间")] [DataType(DataType.DateTime), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}")] public DateTime CreateTime { get; set; } [Display(Name = "最后更新时间")] [DataType(DataType.DateTime), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}")] public DateTime? LastUpdateTime { get; set; } }
View Code
2. 添加DbContext
public class RazorDbContext : DbContext { public RazorDbContext(DbContextOptions<RazorDbContext> options) : base(options) { } public DbSet<Razor.Models.Book> Book { get; set; } }
View Code
3. 安装dotnet-ef(全局安装),终端输入
dotnet tool install --global dotnet-ef
dotnet ef migrations add InitialDb
5. 更新到数据库
dotnet ef database update InitialDb
6. 添加种子数据
public static class SeedData { public static void Initialize(IServiceProvider serviceProvider) { var options = serviceProvider.GetRequiredService<DbContextOptions<RazorDbContext>>(); using (var context = new RazorDbContext(options)) { if (context.Book.Any()) { return; } context.Book.AddRange( new Models.Book { Name = "算法之美", UnitPrice = 26.99m, PublicationDate = DateTime.Parse("2016-08-20"), CreateTime = DateTime.Now }, new Models.Book { Name = "大话设计模式", UnitPrice = 28.03m, PublicationDate = DateTime.Parse("2015-06-12"), CreateTime = DateTime.Now }, new Models.Book { Name = "幸福的陷阱", UnitPrice = 30.59m, PublicationDate = DateTime.Parse("2018-09-13"), CreateTime = DateTime.Now }, new Models.Book { Name = "墨菲定律", UnitPrice = 32.12m, PublicationDate = DateTime.Parse("2018-09-13"), CreateTime = DateTime.Now } ); context.SaveChanges(); } } }
View Code
经过上面的步骤就可以在程序中使用数据库
Razor页面
- 必须是页面上的第一个 Razor 指令
- 默认情况,Url根据文件夹层次结构生成,也可以在@page 后面指定路由
- 可以对参数约束,例如:{id:int}
二、读取数据(以上面模型为例)
1. 创建Index页面
dotnet new page -o=Pages -na="Razor.Pages" -n="Index"
2. PageModel 的OnGet读取数据
public class IndexModel : PageModel { private readonly Data.RazorDbContext _dbContext; public IndexModel(Data.RazorDbContext dbContext) { _dbContext = dbContext; } public List<Models.Book> Books { get; set; } public IActionResult OnGet() { if (_dbContext == null) { return NotFound(); } Books = _dbContext.Book .AsNoTracking() .ToList(); return Page(); } }
View Code
3. 页面展示数据
@page @model IndexModel @{ ViewData["Title"] = "图书管理"; } <table class="table table-bordered text-center"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.Books[0].Name) </th> <th> @Html.DisplayNameFor(model => model.Books[0].UnitPrice) </th> <th> @Html.DisplayNameFor(model => model.Books[0].PublicationDate) </th> <th> @Html.DisplayNameFor(model => model.Books[0].CreateTime) </th> <th > @Html.DisplayNameFor(model => model.Books[0].LastUpdateTime) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model.Books) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.UnitPrice) </td> <td> @Html.DisplayFor(modelItem => item.PublicationDate) </td> <td> @Html.DisplayFor(modelItem => item.CreateTime) </td> <td> @Html.DisplayFor(modelItem => item.LastUpdateTime) </td> <td> <a asp-page="./Edit" asp-route-id="@item.Id">编辑</a> | <a asp-page="./Delete" asp-route-id="@item.Id">删除</a> </td> </tr> } </tbody> </table>
View Code
三、更新数据
1. 创建Edit页面
dotnet new page -o=Pages -na="Razor.Pages" -n="Edit"
2. PageModel拉去数据
public IActionResult OnGet(int? id) { if (id == null) { return NotFound(); } Book = _dbContext.Book .AsNoTracking() .FirstOrDefault(m => m.Id == id); if(Book == null) { return NotFound(); } return Page(); }
View Code
3. 编辑Edit页面
@page "{id:int}" @model Razor.Pages.EditModel @{ ViewData["Title"] = "编辑书本"; } <div class="row"> <div class="col-md-4"> <form method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <input type="hidden" asp-for="Book.Id" /> <div class="form-group"> <label asp-for="Book.Name" class="control-label"></label> <input asp-for="Book.Name" class="form-control" /> <span asp-validation-for="Book.Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Book.UnitPrice" class="control-label"></label> <input asp-for="Book.UnitPrice" class="form-control" /> <span asp-validation-for="Book.UnitPrice" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Book.PublicationDate" class="control-label"></label> <input asp-for="Book.PublicationDate" class="form-control" /> <span asp-validation-for="Book.PublicationDate" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="保存" class="btn btn-primary" /> </div> </form> </div> </div>
View Code
4. OnPost处理请求
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
var model = _dbContext.Book.FirstOrDefault(m => m.Id == Book.Id);
if (model == null)
{
return NotFound();
}
model.Name = Book.Name;
model.PublicationDate = Book.PublicationDate;
model.UnitPrice = Book.UnitPrice;
_dbContext.SaveChanges();
return RedirectToPage("Index");
}
View Code
用asp-for生成的输入框,会加上客户端验证,查看原代码可以发现
<input class="form-control" type="text" data-val="true" data-val-length="书名最大长度为50" data-val-length-max="50" data-val-required="书名不能为空" id="Book_Name" maxlength="50" name="Book.Name" value="大话设计模式" />
它是根据模型定义的验证,生成属性,然后用jquery-validation验证,这样我们没有写一行前端代码就能达到客户端验证效果,微软真的把DRY做到极致。当然后端的验证也是不能漏的
筛选器
Razor 页面筛选器提供的以下方法可在全局或页面级应用:
同步方法:
- OnPageHandlerSelected:在选择处理程序方法后但在模型绑定发生前调用。
- OnPageHandlerExecuting:在执行处理器方法前,模型绑定完成后调用。
- OnPageHandlerExecuted:在执行处理器方法后,生成操作结果前调用。
异步方法:
- OnPageHandlerSelectionAsync:在选择处理程序方法后,但在模型绑定发生前,进行异步调用。
- OnPageHandlerExecutionAsync:在调用处理程序方法前,但在模型绑定结束后,进行异步调用。
public class GlobalPageFilter : IPageFilter { private readonly ILogger _logger; public GlobalPageFilter(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<GlobalPageFilter>(); } public void OnPageHandlerExecuted(PageHandlerExecutedContext context) { _logger.LogDebug("Global Filter OnPageHandlerSelected called."); } public void OnPageHandlerExecuting(PageHandlerExecutingContext context) { _logger.LogDebug("Global Filter OnPageHandlerExecuting called."); } public void OnPageHandlerSelected(PageHandlerSelectedContext context) { _logger.LogDebug("Global Filter OnPageHandlerSelected called."); } }
View Code
2. ConfigureServices添加筛选器
services.AddMvc(options => { options.Filters.Add<Filters.GlobalPageFilter>(); });
public override void OnPageHandlerSelected(Microsoft.AspNetCore.Mvc.Filters.PageHandlerSelectedContext context) { _logger.LogDebug("OnPageHandlerSelected"); } //在执行处理器方法前,模型绑定完成后调用 public override void OnPageHandlerExecuting(Microsoft.AspNetCore.Mvc.Filters.PageHandlerExecutingContext context) { _logger.LogDebug("OnPageHandlerExecuting"); } //在执行处理器方法后,生成操作结果前调用 public override void OnPageHandlerExecuted(Microsoft.AspNetCore.Mvc.Filters.PageHandlerExecutedContext context) { _logger.LogDebug("OnPageHandlerExecuted"); }
View Code