标签:out enc price 图书 change res sele tps 时间
这里介绍了Razor基本用法
准备工作
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; } }
2. 添加DbContext
public class RazorDbContext : DbContext { public RazorDbContext(DbContextOptions<RazorDbContext> options) : base(options) { } public DbSet<Razor.Models.Book> Book { get; set; } }
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(); } } }
经过上面的步骤就可以在程序中使用数据库
Razor页面
二、读取数据(以上面模型为例)
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(); } }
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>
三、更新数据
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(); }
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>
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");
}
用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 页面筛选器提供的以下方法可在全局或页面级应用:
同步方法:
异步方法:
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."); } }
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"); }
示例代码:https://github.com/WilsonPan/AspNetCoreExamples/tree/master/Razor
标签:out enc price 图书 change res sele tps 时间
原文地址:https://www.cnblogs.com/WilsonPan/p/11775622.html