[上課筆記] ASP.NET Core Fundamentals

  • 660
  • 0
  • 2019-12-25

ASP.NET Core Fundamentals

https://github.com/OdeToCode/OdeToFood

這是看線上教學 課程的筆記 加上 自己覺得跟MVC5 相似之處

dotnet CLI
dotnet -h 查看指令
dotnet new 可以看可建立那些專案

Drilling into Data
  -  建立新專案 選Core3.1 =>Web Application
  -  多了wwwroot 裡面放 css , js , lib
  -  預設bootstrap 4.3.1 , jQuery 3.3.1 
  -  沒有裝任何nuget套件
Shared/_Layout 相同於MVC5
NEW  <a asp-page="/Index">Home</a>
NEW  Razor Page
  - 建立Razor Page 除了 List.cshtml 還會多一個 List.cshtml.cs
  -  List.cshtml 有 @page 跟 @model ListModel
  -  List.cshtml.cs  public class ListModel : PageModel  和 public void OnGet()
  -  PageModel  有點Controller的感覺 但是不一樣
  -  ListModel 的 public 屬性 可以直接在 cshtml 呼叫 public string Message { get; set; }  和 <div>@Model.Message</div>
  -  NEW appsettings.json 有點 Web.config =>appSettings 的感覺
  -  要讀取appsettings.json 在建構子用DI注入 IConfiguration 然後 this.config["Message"] 取值
  -  建立新專案 OdeToFood.Core 放 Entity 可以讓網站專案 參考 等於MVC5
  -  建立新專案 OdeToFood.Data 放 取得資料的 interface 方便初期用 InMomory 模擬資料 與 往後替換成資料庫
  -  Startup.cs => ConfigureServices 加入  services.AddSingleton<IRestaurantData, InMomoryRestaurantData>(); 讓DI 知道 注入哪一個物件
  -  Razor 語法 相同於 MVC5

Working with Models and Model Binding
  -  NEW 雙向綁定  <input type="search" class="form-control" asp-for="SearchTerm" />  和   [BindProperty(SupportsGet =true)] public string SearchTerm { get; set; }
  -  連結傳遞參數 可用 asp-route-restaurantId="@item.Id"  和 public void OnGet(int restaurantId)  , asp-route-xxx  是對應參數 所以可以打你命名的變數
     - 產生的網址是  https://localhost:44357/Restaurants/Detail?restaurantId=2
  -  想要網址變這樣 /Restaurants/Detail/2  可以在 Detail.cshtml 加上 @page "{restaurantId:int}" 這樣 asp-route-restaurantId 產生出來的連結 就會是 /Detail/2
  -  public void OnGet 可改成  public IActionResult OnGet 這樣就可以回傳 Page(); 或 RedirectToPage("./NotFound");

Editing Data with Razor Pages
  -  下拉選單  <select class="form-control" asp-for="Restaurant.Cuisine" asp-items="Model.Cuisines"></select>
       - 原本只能在csHtml 呼叫的 HtmlHelper 可以用注入 IHtmlHelper 方法 , Cuisines = HtmlHelper.GetEnumSelectList(); 這樣 asp-items 就可以工作
  -  表單驗證 ModelState.IsValid 相同於MVC5 , modal 也可以設定[Required] , 不同的就是錯誤訊息  <span class="text-danger" asp-validation-for="Restaurant.Name"></span>
  -  兩個page 傳值 可用  TempData["Message"] = "Restaurant saved!"; 接收頁面   [TempData] public string Message { get; set; }
 

Working with SQL Server and the Entity Framework Core
  -  網站 + OdeToFood.Data  => Nuget 安裝 Microsoft.EntityFrameworkCore , Microsoft.EntityFrameworkCore.SqlServer , Microsoft.EntityFrameworkCore.Design , Microsoft.EntityFrameworkCore.Tools
  -  dotnet tool install --global dotnet-ef --version 3.1.0
  -  檢查設定是否正確 => dotnet ef dbcontext info -s ..\OdeToFood\OdeToFood.csproj
  -  建立一個migrations  => dotnet ef migrations add initail -s ..\OdeToFood\OdeToFood.csproj
  -  更新資料庫  => dotnet ef database update -s ..\OdeToFood\OdeToFood.csproj


Building the User Interface
  -  _Layout.cshtml ,  @RenderBody() ,  @RenderSection 相同於 MVC5
  -  MVC5 的Views \ Web.config 改成 _ViewImports.cshtml
  -  partial view
       @foreach (var item in Model.Restaurants)
        {
            <partial name="_Summary" model="item" />
        }

  -  NEW ViewComponent 不同於 partial view , ViewComponent 有自己的model 不是告別人傳入
建立資料夾 \ViewComponents 建立檔案 RestaurantCountViewComponent.cs
public class RestaurantCountViewComponent: ViewComponent
{
        public IRestaurantData RestaurantData { get; }
        public RestaurantCountViewComponent(IRestaurantData restaurantData)
        {
            RestaurantData = restaurantData;
        }
        public IViewComponentResult Invoke()
        {
            var count = RestaurantData.GetCountOfRestaurants();
            return View(count);
        }
}

建立資料夾 \Pages\Shared\Components\RestaurantCount 建立檔案 Default.cshtml
@model int
<div>
    There are @Model restaurants here. <a asp-page="/Restaurants/List">See them all!</a>
</div>

_ViewImports.cshtml 加上 @addTagHelper *, OdeToFood
在csHtml 使用時 <vc:restaurant-count></vc:restaurant-count>  注意 RestaurantCount 變成 restaurant-count 不過打<vc: 會有提示 

Integrating Client-side JavaScript and CSS
  -  NEW wwwroot 是放靜態檔案 例如 js , css , 圖檔
  -  NEW Properties \ launchSettings.json 設定 環境變數
  -  NEW 可以將相同功能的js放在一起 然後又需要時再一起引用 建立 Shared \ _ValidationScriptsPartial.cshtml (放jquery.validate , jquery.validate.unobtrusive)
     有需要用到驗證的頁面 加入 @section Scripts { <partial name="_ValidationScriptsPartial" /> } 
  -  要用 ApiController 的時候 要在 Startup.cs 加入  ConfigureServices => services.AddControllers(); ,  Configure => endpoints.MapControllers();
  -  NEW NPM 是管理html 套件的好東西 可以安裝NuGet套件  OdeToCode.UseNodeModules 在 Startup.cs 加入 Configure => app.UseNodeModules();這樣就可以抓到node_modules資料夾

Working with the Internals of ASP.NET Core
  -  NEW Middleware - Startup.cs 的 Configure 順序很重要

Deploying ASP.NET Core Web Applications
  - 發佈的時候 部屬模式 : 獨立式 表示 會把全部相關DLL 一起發佈 這樣不需要依靠主機上的.NET版本
 - 有用EF migrations 的話 Program.cs 要修改
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();
            MigrateDatabase(host);
            host.Run();
        }
        private static void MigrateDatabase(IHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var db = scope.ServiceProvider.GetRequiredService<OdeToFoodDbContext>();
                db.Database.Migrate();
            }
        }

整理新東西
  - Tag Helpers , asp-page 
  - Razor Page ( 沒說以前的MVC架構還在嗎 ?? )
  - 雙向綁定 BindProperty(SupportsGet =true) 要記得
  - ViewComponent 
  - wwwroot 跟npm 
  - launchSettings.json 設定 環境變數
  - partial JS 的引用
  - Middleware ( 這好像改很大 需要再研究 )
  - EF Core

如果內容有誤請多鞭策謝謝