【ASP.NET Core學習】Razor頁面創建,添加模型,模型驗證,篩選器 ...
這裡介紹了Razor基本用法
- 創建帶PageModel的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();
});
添加資料庫
1. 添加模型[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
4. 添加遷移
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頁面
一、路由 @page指令- 必須是頁面上的第一個 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>(); });二、特定PageModel篩選器 在PageModel裡面重載
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
示例代碼:https://github.com/WilsonPan/AspNetCoreExamples/tree/master/Razor