hi,你好!欢迎访问本站!登录
本站由简数采集腾讯云宝塔系统阿里云强势驱动
当前位置:首页 - 教程 - 杂谈 - 正文 君子好学,自强不息!

【ASP.NET Core进修】Razor页面

2019-11-18杂谈搜奇网29°c
A+ A-

 这里引见了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<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指令
  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<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="&#x4E66;&#x540D;&#x6700;&#x5927;&#x957F;&#x5EA6;&#x4E3A;50" data-val-length-max="50" data-val-required="&#x4E66;&#x540D;&#x4E0D;&#x80FD;&#x4E3A;&#x7A7A;" id="Book_Name" maxlength="50" name="Book.Name" value="&#x5927;&#x8BDD;&#x8BBE;&#x8BA1;&#x6A21;&#x5F0F;" />

它是依据模子定义的考证,生成属性,然后用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<ILogger<Filters.GlobalPageFilter>>();

        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

  选择打赏方式
微信赞助

打赏

QQ钱包

打赏

支付宝赞助

打赏

  移步手机端
【ASP.NET Core进修】Razor页面

1、打开你手机的二维码扫描APP
2、扫描左则的二维码
3、点击扫描获得的网址
4、可以在手机端阅读此文章
未定义标签

本文来源:搜奇网

本文地址:https://www.sou7.cn/282075.html

关注我们:微信搜索“搜奇网”添加我为好友

版权声明: 本文仅代表作者个人观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。请记住本站网址https://www.sou7.cn/搜奇网。

发表评论

选填

必填

必填

选填

请拖动滑块解锁
>>