欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【ASP.NET Core学习】Razor页面

程序员文章站 2023-08-30 14:18:57
【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; }
}

 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
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();
        }
    }
}

 

经过上面的步骤就可以在程序中使用数据库

 

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();
    }
}

  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="&#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(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>();
});
二、特定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");
}

 

示例代码:https://github.com/wilsonpan/aspnetcoreexamples/tree/master/razor