【ASP.NET Core学习】Razor页面

 这里介绍了Razor基本用法

  1. 创建带PageModel的Razor 页面
  2. 使用数据库
  3. 展示数据
  4. 更新数据
  5. 筛选器

准备工作

  1. 初始化空的项目(终端输入:dotnet new web -n=Razor)
  2. Nuget添加Microsoft.EntityFrameworkCore.SqlServer 和 Microsoft.EntityFrameworkCore.Design             
  3. 添加必要服务

   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 options)
        : base(options)
    {
        
    }

    public DbSet 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>();
        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指令
  1. 必须是页面上的第一个 Razor 指令
  2. 默认情况,Url根据文件夹层次结构生成,也可以在@page 后面指定路由
  3. 可以对参数约束,例如:{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 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"] = "图书管理";
}
class="table table-bordered text-center">
    
        @foreach (var item in Model.Books)
        {
            
        }
    
@Html.DisplayNameFor(model => model.Books[0].Name) @Html.DisplayNameFor(model => model.Books[0].UnitPrice) @Html.DisplayNameFor(model => model.Books[0].PublicationDate) @Html.DisplayNameFor(model => model.Books[0].CreateTime) @Html.DisplayNameFor(model => model.Books[0].LastUpdateTime)
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.UnitPrice) @Html.DisplayFor(modelItem => item.PublicationDate) @Html.DisplayFor(modelItem => item.CreateTime) @Html.DisplayFor(modelItem => item.LastUpdateTime) "./Edit" asp-route-id="@item.Id">编辑 | "./Delete" asp-route-id="@item.Id">删除
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:在调用处理程序方法前,但在模型绑定结束后,进行异步调用。
一、全局筛选器
  1. 创建GlobalPageFilter类,实现IPageFilter接口
public class GlobalPageFilter : IPageFilter
{
    private readonly ILogger _logger;

    public GlobalPageFilter(ILogger logger)
    {
        _logger = logger;
    }

    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. 创建过滤器工厂类,实现IFilterFactory接口

public class GlobalPagerFilterWithFactory : IFilterFactory
{
    public bool IsReusable => false;

    public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
    {
        var logger = serviceProvider.GetService>();

        return new Filters.GlobalPageFilter(logger);
    }
}
View Code

  3. ConfigureServices添加RazorPage选项

services.AddRazorPages()
        .AddRazorPagesOptions(options =>
        {
            options.Conventions.ConfigureFilter(new Factories.GlobalPagerFilterWithFactory());
        });

 

二、特定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

你可能感兴趣的:(【ASP.NET Core学习】Razor页面)