iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 12
1
Microsoft Azure

Azure 的自我修煉系列 第 12

Day12 實作官網 ASP.NET Core 教學(四)

5. 更新 Razor 頁面

更新產生的程式碼

修改 Models/Article.cs

  1. 修改 ReleaseDate 顯示欄位名稱與格式
  2. 改變 Count 欄位型態
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace PellokITHome.Models
{
    public class Article
    {
        public int ID { get; set; }
        public string Title { get; set; }
        
        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}")]
        public DateTime ReleaseDate { get; set; }
        public string Link { get; set; }
        public int
 Count { get; set; }
    }
}

Display 屬性指定要顯示的欄位名稱
DataType 屬性指定資料的類型 (Date),因此不會顯示儲存在欄位中的時間資訊
DisplayFormat 定義顯示格式

資料庫異動紀錄

#
dotnet ef migrations list
dotnet ef migrations add UpdateArticleCountType
dotnet ef migrations list

https://ithelp.ithome.com.tw/upload/images/20200911/200726514fzPk8MtCP.png

資料庫更新

dotnet ef database update

遇到問題 "SQLite does not support this migration operation"
https://ithelp.ithome.com.tw/upload/images/20200911/20072651vR232OwU6J.png

SQLite EF Core 資料庫提供者限制

後來指令刪除DB重建

# 刪除 DB
dotnet ef database drop
# 刪除 UpdateArticleCountType
dotnet ef migrations remove
# 刪除 InitialCreate
dotnet ef migrations remove
# 增加 InitCreate
dotnet ef migrations add InitCreate
# 創建 DB
dotnet ef database update

創建後查看服務
https://ithelp.ithome.com.tw/upload/images/20200911/20072651D0QSgVs3pR.png

新增路由範本

修改 Pages/Articles/Edit.cshtml

@page 
改成
## 對使用 "{id:int}" 路由範本的頁面提出的要求若未包含整數,將傳回 HTTP 404 (找不到) 錯誤
@page "{id:int}"
或
## 若要使識別碼成為選擇性,請將 ? 附加至路由條件約束
@page "{id:int?}"

查看結果,原本是?id=1 變成只接用 url 方式
https://ithelp.ithome.com.tw/upload/images/20200911/200726519LGWxkA9WD.png

檢閱並行存取例外狀況處理

當一個用戶端刪除電影,而另一個用戶端發佈對電影的變更時,先前的程式碼會偵測並行存取例外狀況。
若要測試 catch 區段:
在 catch (DbUpdateConcurrencyException)上設定中斷點
針對電影選取 [編輯],進行變更,但不要輸入 [儲存]
在另一個瀏覽器視窗中,選取相同電影的 Delete 連結,然後刪除電影。
在先前的瀏覽器視窗中,發佈對電影的變更。
實際執行程式碼可能需要偵測並行存取衝突。 如需詳細資訊,請參閱處理並行存取衝突。

6. 新增搜尋

修改 Pages/Article/index.cshtml.cs
增加
[BindProperty(SupportsGet = true)]
public string SearchString { get; set; }
修改 OnGetAsync() funtion 內容

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using PellokITHome.Data;
using PellokITHome.Models;

namespace PellokITHome.Pages.Articles
{
    public class IndexModel : PageModel
    {
        private readonly PellokITHome.Data.PellokITHomeContext _context;

        public IndexModel(PellokITHome.Data.PellokITHomeContext context)
        {
            _context = context;
        }

        public IList<Article> Article { get;set; }

        [BindProperty(SupportsGet = true)]
        public string SearchString { get; set; }
            
        public async Task OnGetAsync()
        {
            var articles = from a in _context.Article select a;
            if (!string.IsNullOrEmpty(SearchString))
            {
                articles = articles.Where(s => s.Title.Contains(SearchString));
            }
            
            Article = await articles.ToListAsync();
        }
    }
}

修改 Pages/Article/index.cshtml
修改 第一行的Page 帶入searchString參數
增加一個 form 可以讓使用者輸入 Filter搜尋

@page "{searchString?}"
@model PellokITHome.Pages.Articles.IndexModel

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-page="Create">Create New</a>
</p>

<form>
    <p>
        Title: <input type="text" asp-for="SearchString" />
        <input type="submit" value="Filter" />
    </p>
</form>

https://ithelp.ithome.com.tw/upload/images/20200911/20072651EGvT31gURe.png

7. 新增欄位

在 Models/Articles 增加 category 欄位

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace PellokITHome.Models
{
    public class Article
    {
        public int ID { get; set; }
        public string Title { get; set; }
        
        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}")]
        public DateTime ReleaseDate { get; set; }
        public string Link { get; set; }
        public int Count { get; set; }
        public string Category {get; set;}
    }
}

種子資料增加分類欄位資訊
增加 Category = "鐵人賽"

context.Article.AddRange(
    new Article
    {
        Title = "Day01 Azure 的自我修煉",
        ReleaseDate = DateTime.Parse("2020-09-01"),
        Link = "https://ithelp.ithome.com.tw/articles/10233277",
        Count = 0,
        Category = "鐵人賽"
    },
}

由於有更新資料表欄位,所以要重建資料庫

dotnet ef migrations add ArticleAddCategory
dotnet ef database drop
dotnet ef database update

https://ithelp.ithome.com.tw/upload/images/20200911/20072651FFOjTgkcK2.png

重新啟動服務
https://ithelp.ithome.com.tw/upload/images/20200911/20072651qUUUFI99KA.png

8. 新增驗證

將驗證規則新增至文章

修改 Models/Article.cs

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace PellokITHome.Models
{
    public class Article
    {
        public int ID { get; set; }
        [StringLength(60, MinimumLength = 3)]
        [Required]
        public string Title { get; set; }
        
        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}")]
        [Required]
        public DateTime ReleaseDate { get; set; }
        public string Link { get; set; }
        public int Count { get; set; }
        
        [RegularExpression(@"^[A-Z]+[a-zA-Z]*$")]
        [StringLength(30)]
        public string Category {get; set;}
    }
}

驗證屬性會指定您想要對套用目標模型屬性強制執行的行為

伺服器端驗證

在瀏覽器中停用 JavaScript 時,提交含有錯誤的表單將發佈到伺服器。

if (!ModelState.IsValid)
{
    return Page();
}

使用 DataType 屬性

使用 DataType 來控制欄位屬性

[Display(Name = "Release Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}")]
[Required]
public DateTime ReleaseDate { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z]*$")]
[StringLength(30)]
public string Category {get; set;}

更新資料庫,
由於SQLite 遇到AlterColumnOperation 問題,所以我們直接重建DB
直接移除 Migrations 資料夾,再直接重建

# 移除 Migrations 資料夾
rm -rf Migrations
# 增加 InitCreate
dotnet ef migrations add InitCreate
# 創建 DB
dotnet ef database update

提交版本

# 查看原始碼修改狀態
git status
# 加入索引
git add .
# 提交版本
git commit -m "Update Article"
# 更新遠端倉庫
git push

相關連結:

上一篇 Day11 實作官網 ASP.NET Core 教學(三)
下一篇 Day13 部署 Webapp 使用 SQL服務


上一篇
Day11 實作官網 ASP.NET Core 教學(三)
下一篇
Day13 部署 Webapp 使用 SQL服務
系列文
Azure 的自我修煉30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言