發表文章

目前顯示的是 2022的文章

[ASP.NET Core 6 MVC] 使用 Dapper

圖片
這篇是參考自 Code Maze : Using Dapper with ASP.NET Core Web API 的教學,練習後自己做了一個筆記。以下使用 Visual Studio 2022,建立專案為 ASP.NET Core Web 應用程式 (Model-View-Controller)使用 .NET 6.0 架構,方案名稱為 DemoDapper。以下會講得比較瑣碎詳細,因為以前開始學 .NET 4.8 MVC 時欠缺這樣 step by step 的懶人包,希望可以幫到一些初學者。(以下忽略 null 值判斷與 try catch 處理) 安裝 Dapper 套件 取得連線字串和設定 appsettings.json 新增介面與類別檔案 Controller 與 View 安裝 Dapper 套件 在「方案總管」視窗,對「相依性」按滑鼠右鍵,點選「管理 NuGet 套件」(或是「工具」,「NuGet 套件管理員」點選「管理方案的 NuGet 套件」) 於「瀏覽」標籤頁搜尋以下兩個,選擇適合的版本安裝,下圖是已安裝好的標籤頁: Dapper 作者 Sam Safforn, Marc Gravell, Nick Craver System.Data.SqlClient 作者 Microsoft 常常看教學還要安裝一個和 Configuration 相關的,但我安裝以上兩個套件即可。 取得連線字串和設定 appsettings.json 以我的本機 MS SQL 為例,機器「.」使用Windows 驗證登入,有一個資料庫叫「dbtest」: 回到 Visual Studio,點選「檢視」,「伺服器總管」,在伺服器總管視窗的「資料連接」上或空白處按滑鼠右鍵,點選「加入連接」: 「選擇資料來源」頁面,「資料來源」選擇 Microsoft SQL Server,「資料提供者」選擇 .NET Framework Data Provider for SQL Server,點選繼續: 「加入連接」頁面在「伺服器名稱」填入「.」驗證選 Windows 驗證,然後下方「選取或輸入資料庫名稱」就可以下拉找資料庫了,我選了前面說的 dbtest 資料庫。當然如果 SQL Server 在...

[ASP.NET Core 6 MVC] 使用 Session

圖片
這篇是參考自 C# Corner : How To Use Sessions In ASP.NET Core 的教學,不過文中是 .NET 5,所以和 .NET 6 設定上有點差異,再加上和過去 .NET 4 使用 namespace 後就可以無腦使用 Session 不太一樣,就做了這個筆記,以下範例使用 Visual Studio 2022,建立專案為 ASP.NET Core Web 應用程式 (Model-View-Controller)使用 .NET 6.0 架構。 下載 Session 套件 設定 Program.cs 使用 Session ,存取字串和整數 用 Json 序列化使 Session 存取物件 將序列化寫成擴充方法 下載 Session 套件 在方案總管視窗對「相依性(Dependencies)」滑鼠右鍵,選擇「管理 NuGet 套件」: 在「瀏覽」標籤頁中搜尋「Session」,應該最多人下載的是 Microsoft 的「Microsoft.AspNetCore.Session」: 依版本點選「安裝」(這裡我選最新穩定版 2.2.0): 若有變更警告點選「OK」,授權提示點選「I Accept」: 裝好後剛剛的頁面應該會顯示目前版本,且原本的「安裝」變成「解除安裝」,就可以關掉 NuGet 分頁了。 設定 Program.cs 再來要設定 Program.cs 設定檔,至方案總管視窗雙擊此檔案: 原本檔案的最上面是: var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); 在此給容器加入 Session service: var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithView...

[ASP.NET MVC] 匯出 .csv 檔案

圖片
常見的匯出檔案有 .pdf .xls .ods .csv,下面筆記最簡單的 .csv 檔,可用常見的 Microsoft Office Excel 或 LibreOffice Calc 等報表軟體開啟: 產生檔案下載 列出清單結果 匯出 .csv 檔案 產生檔案下載 Controller 可以用 return File(); 來做到檔案下載,引數分別為 byte[] 的檔案內容,string 表示的檔案類型和 string 下載後檔案名稱,而 byte[] 類型可用 System.Text.Encoding.Default.GetBytes() 方法來獲得位元組序列,以下為名稱 Demo 的 Controller 程式碼: using System.Text; namespace prjMVC.Controllers { public class DemoController : Controller { public ActionResult GetFiles(string output) { string fileName = "output.txt"; // 存成檔名 byte[] fileContent = Encoding.Default.GetBytes(output); // 轉成位元組序列 return File(fileContent, "text/plain", fileName); } } } 以上 Action 在瀏覽器輸入 ~/Demo/GetFiles?output=xxxx 的網址,或是 View 中有 @Html.ActionLink("下載", "GetFiles", new { output = "xxxx" }) 產生的超連結被點擊時,瀏覽器就會下載一個文字檔案 output.txt: 下面就是傳入 output 字串 "測試文字" 得到的下載文字檔案: 列出清單結果 這個...

[ASP.NET MVC] Html.Partial() 和 Html.Action()

圖片
ASP.NET MVC 的 View 中可以有 Partial View (部份檢視),而且可以繫結不一樣的 Model,例如 View 繫結叫做 VM_Big 的物件,可以在 Partial View 繫結叫做 QM_Small 的物件,下面是專案 prjMvc 下的 ~/Models 裡的兩個類別: VM_Big namespace prjMVC.Models { public class VM_Big { public QM_Small Small { get; set; } } } 和 QM_Small namespace prjMVC.Models { public class QM_Small { public DateTime Time { get; set; } public string Description { get; set; } } } 這裡讓 VM_Big 類別下有一個屬性,是 QM_Small 物件,而 QM_Small 類別下有時間物件 Time 和字串 Description,然後在 Controller 中寫一個 Action 叫 Index: using prjMVC.Models; namespace prjMVC.Controllers { public class DemoController : Controller { public ActionResult Index() { VM_Big big = new VM_Big(); big.Small = new QM_Small(); big.Small.Time = DateTime.Now; big.Small.Description = "現在時間"; return View(big); } } } 程式碼如上,實體化一個 VM_Big 的物件叫 big,並將他的屬性 Small 用 QM_Small 實體化,並指定屬性時間物件 Time 為 DateTime....

[ASP.NET MVC] @Html.DisplayFor() 、@Html.DisplayTextFor()、@Html.DisplayNameFor() 和 @Html.EditorFor()

圖片
使用過 ASP.NET MVC 內建產生範本功能的人一定對標題的四個方法不陌生,如下有一 Model UserInfo 這樣設計: Model 各屬性的資料型態 using System.ComponentModel; namespace prjMVC.Models { public class UserInfo { [DisplayName("姓名")] public string Name { get; set; } [DisplayName("年齡")] public int Age { get; set; } [DisplayName("體重")] public double Weight { get; set; } [DisplayName("生日")] public DateTime Birthday { get; set; } [DisplayName("已婚")] public bool IsMarried { get; set; } } } 在 Controller 傳到 View: UserInfo user = new UserInfo { Name = "Billy", Age = 25, Weight = 74.5, Birthday = new DateTime(1997, 5, 2), IsMarried = true, }; return View(user); DisplayFor() 方法 在 View 中,@Html.DisplayFor() 會依據資料和型態來顯示: @model prjMvc.Models.UserInfo <h2>DisplayFor</h2> <div>@Html.DisplayFor(m => m.Name)</div> <div...

[ASP.NET MVC] @Html.BeginForm() 和 <form>

圖片
要產生 <form> 要使用 @Html.BeginForm() 方法,不過不能單獨呼叫,因為 <form> 要有 </form> ,所以要利用 @using() { } 包住。下面舉例,在 Home Controller 裡寫一個 Action 叫 Create : public ActionResult Create() { return View(); } 在 Create 的 View 中,如下使用 BeginForm() 方法: @using(Html.BeginForm()) { } // 會產生: <form action="/Home/Create" method="post"></form> 會發現 action 屬性已自動填上本身 Action 的位址,而且 method 自動使用 Post,這些是 BeginForm() 預設的選項,也可以更改: @using(Html.BeginForm("CreateDetail" // 目標 Action , "Order" // 目標 Controll , FormMethod.Get)) // 使用 method 方法 { } // 會產生: <form action="/Order/CreateDetail" method="get"><form> 如上,action URL 會更改,且 method 也改成使用 Get 方法。 也可以用五個引數,在第三個引數帶入 route value ,第五個引數帶入 HTML Attribute,都是使用匿名類別帶入,如下: @using(Html.BeginForm("CreateDetail" , "Order...

[ASP.NET MVC] @Html.Hidden() 、@Html.HiddenFor() 和 <input type="hidden">

圖片
有時候傳輸 form data 有一種需求,就是有資料需要靠 name 繫結然後傳到後端做處理,但又不想讓使用者看到,這時就常常使用 <input type="hidden"> ,例如商品 ID 會在 View 放在 <input type="hidden" name="productId" value="ab0123456"> 或類似的應用。而產生這樣的標籤可以使用 @Html.Hidden() 方法,一個引數時表示 id 和 name: @Html.Hidden("productId") // 會產生: <input id="productId" name="productId" type="hidden" value="" /> 若要馬上將值帶入 value,使用第二個引數: @Html.Hidden("productId" , "ab0123456") // 會產生: <input id="productId" name="productId" type="hidden" value="ab0123456" /> 三個引數時可帶入 HTML Attribute 增加樣式或事件,要使用匿名類別(但好像沒什麼會這樣的需求): @Html.Hidden("productId" , "ab0123456" , new { onchange = "checkValue()" } ) // 會產生: <input id="productId" name="productId" onchange="checkValue()" type=...

[ASP.NET MVC] @Html.DropDownList() 、@Html.DropDownListFor() 和 <select> 與<option>

圖片
要產生 <select> 和 <option> ,利用 System.Web.Mvc 命名空間下的 SelectListItem 類型,可製造出下拉選單,在 Controller 或 Model 中先建好資料: using System.Web.Mvc; List<SelectListItem> cities = new List<SelectListItem>() { new SelectListItem{ Text = "台南", Value = "Tainan" }, new SelectListItem{ Text = "高雄", Value = "Kaohsiung" }, new SelectListItem{ Text = "台中", Value = "Taichiung" }, new SelectListItem{ Text = "桃園", Value = "Taoyuan" }, new SelectListItem{ Text = "台北", Value = "Taipei" } }; cities.Where(c => c.Text == "桃園") .FirstOrDefault() .Selected = true; // Selected 屬性表示預設是哪一個選項被選取 ViewBag.cities = cities; // 利用 ViewBag 將資料帶去 View return View(); 然後在 View 中: @{ // ViewBag 不用轉型,但要先宣告, IEnumerable<SelectListItem> cities = ViewBag.cities; // 不能直接...

[ASP.NET MVC] @Html.CheckBox() 、@HtmlCheckBoxFor() 和 <input type="checkbox">

圖片
要產生勾選方塊的 <input type="checkbox">,使用 @Html.CheckBox(),一個引數時表示 id 和 name,如下: @Html.CheckBox("isMarried")已婚 // 會產生: <input id="isMarried" name="isMarried" type="checkbox" value="true" /> <input name="isMarried" type="hidden" value="false" />已婚 會看到產生的 HTML 會有兩個,一個 @Html.CheckBox 會產生兩個 <input>,一個是 type="checkbox" 另一個是 type="hidden",畫面上是看不到 hidden 的,用意是在前端沒有勾選 checkbox 時,後端 form 會得到該 name 的 value 是 false,而前端勾選 checkbox 時後端會得到 true。 第二個引數是預設是否勾選的布林值,會增加 checked 屬性: @Html.CheckBox("isMarried" , true)已婚 // 會產生: <input checked="checked" id="isMarried" name="isMarried" type="checkbox" value="true" /> <input name="isMarried" type="hidden" value="false" />已婚 可在第三個引數加上 HTML 屬性,例如樣式或事件: @Html.CheckBox("isMarr...

[ASP.NET MVC] @Html.RadioButton() 、@Html.RadioButtonFor() 和 <input type="radio">

圖片
要產生單選的 <input type="radio"> 要使用 @Html.RadioButton(),而且至少要兩個引數: @Html.RadioButton("grade" // 第一個引數做為 id 和 name , 1)一年級<br /> // 第二個引數為 value @Html.RadioButton("grade" , 2)二年級<br /> @Html.RadioButton("grade" , 3)三年級<br /> // 會產生: <input id="grade" name="grade" type="radio" value="1" />一年級<br /> <input id="grade" name="grade" type="radio" value="2" />二年級<br /> <input id="grade" name="grade" type="radio" value="3" />三年級<br /> 同 name 下會算為同一個 group,所以不需要再帶 group 屬性。如果要指定哪個選項是預設點選的,使用第三個引數: @Html.RadioButton("grade" , 1)一年級<br /> @Html.RadioButton("grade" , 2 , true)二年級<br /...

[ASP.NET MVC] @Html.Password() 、@Html.PasswordFor() 和 <input type="password">

圖片
密碼欄位可用 @Html.Password() 快速產生,一個引數時是表示 id 和 name: @Html.Password("pwd") // 可產生: <input id="pwd" name="pwd" type="password" /> 兩個引數時第二個是預設填入的值: @Html.Password("pwd" , "abc1234") // 可產生: <input id="pwd" name="pwd" type="password" value="abc1234" /> 三個引數時可在第三個引數用匿名類別 new { } 帶入 HTML 屬性: @Html.Password("pwd" , null , new { placeholder = "請輸入密碼", maxLength = "15" }) // 可產生: <input id="pwd" maxLength="15" name="pwd" placeholder="請輸入密碼" type="password" /> 我們常常在登入帳號時,也會設計 Model 或 ViewModel: public class VMLogin { public string Account { get; set; } public string Password { get; set; } } 例如 Controller 帶入一個 VMLogin 到 View: VMLogin vModel = new VMLogin(); return View(vModel); 在 View 中可用強型別的 PasswordFor() 快速產...

[ASP.NET MVC] @Html.Label() 、@Html.LabelFor() 和 <label>

圖片
<input> 常常搭配 <label> 方便點選,產生的方法是 @Html.Label(),一個引數的寫法如下: @Html.Label("帳號:") // 會產生: <label for="帳號:">帳號:<label> 但是上面的結果通常不是我們要的,for 屬性要填別的 <input> 的 id ,常常是變數,這就要用兩個引數: @Html.Label("txtAccount" // 成為 for,填的是點選後會 focus 到的目標 id , "帳號:") // 成為 textContent ,顯示的文字內容 // 會產生: <label for="txtAccount">帳號:<label> 也可用第三個引數帶入 HTML 屬性,使用匿名類別 new { } : @Html.Label("txtAccount": , "帳號:" , new { @class = "label-title" } ) // 會產生: <label class="label-title" for="txtAccount">帳號:<label> 以上因為 class 是保留字所以前面要加上 @ 。另外有繫結 Model 時可用強型別的方法,例如這是從 Controller 帶往 View 的 ViewModel: public class VMLogin { public string Account { get; set; } public string Password { get; set; } } VMLogin vModel = new VMLogin(); return View(vModel); 而 View 中可用 LabelFor(...