1、創建一個Asp.Net Core Web應用程式
1.1、打開VS2019 新建專案

1.2、選好專案位置后進入選擇界面,選擇Web應用程式

1.3、進去的頁面結構如下

Pages 檔案夾:包含 Razor 頁面和支持檔案, 每個 Razor 頁面都是一對檔案:
- 一個 .cshtml 檔案,其中包含使用 Razor 語法的 C# 代碼的 HTML 標記 ,
- 一個 .cshtml.cs 檔案,其中包含處理頁面事件的 C# 代碼 ,
wwwroot 檔案夾:包含靜態檔案,如 HTML 檔案、JavaScript 檔案和 CSS 檔案,
appSettings.json:包含配置資料,如連接字串,
Program.cs:包含程式的入口點,
Startup.cs:包含配置應用行為的代碼,
運行起來如果提示要安裝證書的直接點是就可以了,出現WelCome就表示可以了
2、添加模型
2.1、在這里搭建“商品”模型的基架, 確切地說,基架工具將生成頁面,用于對“商品”模型執行創建、讀取、更新和洗掉 (CRUD) 操作,
右擊專案名稱添加檔案夾Models,在Models新檔案夾里新建一個模型類Shop
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace CoreRazorPages.Models { /// <summary> /// 商品類 /// </summary> public class Shop { [Display(Name="ID")] public int ID { get; set; } [Display(Name = "Guid")] public string Guid { get; set; } [Display(Name = "名稱")] public string Name { get; set; } [Display(Name = "價格")] public decimal Price { get; set; } [Display(Name = "添加日期")] [DataType(DataType.Date)] public DateTime AddTime { get; set; } } }
3、添加基架
3.1、右擊Pages檔案夾添加一個檔案夾Shop,然后右擊Shop>添加>新搭建基架的專案>使用物體框架生成Razor頁面(CRUD)模型類選擇Shop,資料庫背景關系點擊右邊的+號

3.2、生成專案,如果報錯Shop就加上命名空間,這里是因為檔案夾Shop名稱跟類名Shop一樣
專案檔案夾多了個Data那是資料庫背景關系,還有組態檔里面也加了資料庫訪問的字串在appsetting.json檔案夾里

3.3、更改資料庫鏈接
打開appsettiong.json檔案修改里面的資料庫鏈接字串,然后點工具>nuget包管理器>程式包管理控制臺依次輸入Add-Migration InitialCreate、Update-Database,警告不要管他(程式員不怕警告就怕錯誤 哈哈)
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { //原來生成的Server=(localdb)\\mssqllocaldb;Database=CoreRazorPagesContext-10c906a7-1959-4967-9659-0fcbfe8b7d16;Trusted_Connection=True;MultipleActiveResultSets=true "CoreRazorPagesContext": "Data Source=服務器地址;Initial Catalog=資料庫名User ID=用戶名;Password=密碼" } }

看生成的資料庫

3.4、修改檔案夾Shared下的布局_Layout.cchtml添加Shop導航
看起來有點像winform的服務器控制元件一樣哈哈,asp-area是區域名,現在沒有 asp-page是指Razor的位置這里是Shop/Index
<header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container"> <a class="navbar-brand" asp-area="" asp-page="/Index">CoreRazorPages</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a> </li> <li > <a asp-area="" asp-page="Shop/Index">商品</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a> </li> </ul> </div> </div> </nav> </header>
3.5、添加一些資料在Shop中,在Data檔案件下面添加一個類 AddDefaultData,然后修改程式入口main 方法,
從依賴關系注入容器獲取資料庫背景關系實體>呼叫 InitData方法,并將背景關系傳遞給它、方法完成時釋放背景關系
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; //添加命名空間 using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using CoreRazorPages.Models; namespace CoreRazorPages.Data { public class AddDefaultData { /// <summary> /// 添加資料 /// </summary> /// <param name="serviceProvider"></param> public static void InitData(IServiceProvider serviceProvider) { using (var db = new CoreRazorPagesContext(serviceProvider.GetRequiredService<DbContextOptions<CoreRazorPagesContext>>())) { //如果有資料就不添加了 if (db.Shop.Any()) { return; } //添加10條初始資料 for(var i=0;i<10;i++) { var model = new Shop { Name = "商品"+i.ToString(), Guid = Guid.NewGuid().ToString("N"), Price = i + 0.66M, AddTime = DateTime.Now }; db.Shop.AddRange(model); } db.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; //添加命名空間 using Microsoft.Extensions.DependencyInjection; using CoreRazorPages.Data; namespace CoreRazorPages { public class Program { public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope=host.Services.CreateScope()) { var services = scope.ServiceProvider; try { AddDefaultData.InitData(services); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "添加初始資料失敗"); } } host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
資料庫依賴注入在staup.cs里面已經自己生成好了
public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); //資料庫連接 services.AddDbContext<CoreRazorPagesContext>(options => options.UseSqlServer(Configuration.GetConnectionString("CoreRazorPagesContext"))); }
然后啟動 點到商品導航上面資料就有了,也可以一些基本的操作(CRUD)

4、添加搜索
添加名稱,guid的搜索,在Pages檔案夾下面的Shop檔案夾下面的Index.cchtml.sc打開 修改
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 CoreRazorPages.Data; using CoreRazorPages.Models; namespace CoreRazorPages.Pages.Shop { public class IndexModel : PageModel { private readonly CoreRazorPages.Data.CoreRazorPagesContext _context; public IndexModel(CoreRazorPages.Data.CoreRazorPagesContext context) { _context = context; } /// <summary> /// 模型List /// </summary> public IList<CoreRazorPages.Models.Shop> Shop { get;set; } [BindProperty(SupportsGet = true)] public string SearchName { get; set; } [BindProperty(SupportsGet = true)] public string SearchGuid { get; set; } public async Task OnGetAsync() { var model = _context.Shop.Where(x=>x.ID>0); if (!string.IsNullOrEmpty(SearchName)) model = model.Where(x => x.Name.Contains(SearchName)); if (!string.IsNullOrEmpty(SearchGuid)) model = model.Where(x => x.Guid.Contains(SearchGuid)); Shop = await model.ToListAsync(); } } }
在Index.cshtml里面添加
<p> <a asp-page="Create">Create New</a> </p> <form> <p> 名字: <input type="text" asp-for="SearchName" /> Guid: <input type="text" asp-for="SearchGuid" /> <input type="submit" value="搜索" /> </p> </form>
SearchName 、SearchGuid:包含用戶在搜索文本框中輸入的文本, SearchString 也有 [BindProperty] 屬性, [BindProperty] 會系結名稱與屬性相同的表單值和查詢字串, 在 GET 請求中進行系結需要 (SupportsGet = true),

5、添加欄位,驗證
5.1在模型檔案Shop.cs添加一個欄位Remark
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace CoreRazorPages.Models { /// <summary> /// 商品類 /// </summary> public class Shop { [Display(Name="ID")] public int ID { get; set; } [Display(Name = "Guid")] public string Guid { get; set; } [Display(Name = "名稱")] public string Name { get; set; } [Display(Name = "價格")] public decimal Price { get; set; } [Display(Name = "添加日期")] [DataType(DataType.Date)] public DateTime AddTime { get; set; } /// <summary> /// 新加欄位、驗證 /// </summary> [Required]//必填 [StringLength(10,ErrorMessage ="{0}最大長度10 必填")]//最大長度 [RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]//驗證格式 public string Ramake { get; set; } } }
5.2nuget包管理器>程式包管理控制臺依次輸入Add-Migration Remake、Update-Database,

5.3、編輯Shop檔案夾下面的Index.cshtml、Create.cshtml、Delete.cshtml、Details.cshtml、Edit.cshtml檔案添加Remake欄位
<td> @Html.DisplayFor(modelItem => item.Ramake) </td> <div class="form-group"> <label asp-for="Shop.Ramake" class="control-label"></label> <input asp-for="Shop.Ramake" class="form-control" /> <span asp-validation-for="Shop.Ramake" class="text-danger"></span> </div> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Shop.Ramake) </dd> <div class="form-group"> <label asp-for="Shop.Ramake" class="control-label"></label> <input asp-for="Shop.Ramake" class="form-control" /> <span asp-validation-for="Shop.Ramake" class="text-danger"></span> </div>
5.4、運行起來測驗看

6、代碼總結:
- Razor 頁面派生自 PageModel, 按照約定,PageModel 派生的類稱為 <PageName>Model, 此建構式使用依賴關系注入將 RazorPagesMovieContext 添加到頁, 所有已搭建基架的頁面都遵循此模式,對頁面發出請求時,OnGetAsync 方法向 Razor 頁面回傳影片串列, 呼叫 OnGetAsync 或 OnGet 以初始化頁面的狀態, 在這種情況下,OnGetAsync 將獲得影片串列并顯示出來,
當 OnGet 回傳 void 或 OnGetAsync 回傳 Task 時,不使用任何回傳陳述句, 當回傳型別是 IActionResult 或 Task<IActionResult> 時,必須提供回傳陳述句
-
@page 指令:@page Razor 指令將檔案轉換為一個 MVC 操作,這意味著它可以處理請求, @page 必須是頁面上的第一個 Razor 指令, @page 是轉換到 Razor 特定標記的一個示例
- @model 指令指定傳遞給 Razor 頁面的模型型別, 在前面的示例中,@model 行使 PageModel 派生的類可用于 Razor 頁面, 在頁面上的 @Html.DisplayNameFor 和 @Html.DisplayFor HTML 幫助程式中使用該模型,
現在開始對Razor頁面有一定了解,大多數代碼都是系統自己生成的,資料庫背景關系類、依賴注入、我也是對Core還不怎么熟悉不知道怎么學習跟著做就行了,對后面肯定有很大的幫助,
原文地址:https://www.cnblogs.com/w5942066/p/12597712.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/50988.html
標籤:.NET Core
