iT邦幫忙

2021 iThome 鐵人賽

DAY 15
0
Modern Web

從實作學習ASP.NET Core - 30天的購物網站系列 第 15

【從實作學習ASP.NET Core】Day15 | 後台 | 自定義使用者欄位

延續昨天的會員功能,預設會員資訊欄位只有 Email 和 Password,今天要加上一些欄位讓會員資料更完整


自定義使用者

打開 Areas/Identity/Data/OnlineShopUser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace OnlineShopCMS.Areas.Identity.Data
{
    public class OnlineShopUser : IdentityUser
    {
        public string Name { get; set; }                //名稱
        public DateTime DOB { get; set; }               //生日
        public GenderType Gender { get; set; }          //性別
        public DateTime RegistrationDate { get; set; }  //註冊日期
    }

    public enum GenderType
    {
        Male, Female, Unknown
    }
}

移轉資料庫

有更新模型就要更新資料表內容
Add-Migaration -Context OnlineShopUserContext
Update-Database -Context OnlineShopUserContext
( 這時候因為專案裡有兩個以上的DbContext,需要用 -Context 來指定對象 )


資料表出現新加的欄位了

註冊頁面

接著變更 Register 頁面
Areas/Identity/Pages/Account/Register.cshtml 加入 Name, DOB, Gender 欄位:

<div class="form-group">
    <label asp-for="Input.Name"></label>
    <input asp-for="Input.Name" class="form-control" />
    <span asp-validation-for="Input.Name" class="text-danger"></span>
</div>
<div class="form-group">
    <label asp-for="Input.DOB"></label>
    <input asp-for="Input.DOB" class="form-control" />
    <span asp-validation-for="Input.DOB" class="text-danger"></span>
</div>
<div class="form-group">
    <label asp-for="Input.Gender" class="control-label"></label>
    <select asp-for="Input.Gender" class="form-control"
        asp-items="Html.GetEnumSelectList<GenderType>()">
        <option>Select type ...</option>
    </select>
    <span asp-validation-for="Input.Gender" class="text-danger"></span>
</div>

後端程式碼 Register.cshtml.csInputModelOnPostAsync()加入相關欄位

[Required]
[DataType(DataType.Text)]
[Display(Name = "Full name")]
public string Name { get; set; }

[Required]
[Display(Name = "Birth Date")]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }

[Required]
[Display(Name = "Gender")]
public GenderType Gender { get; set; }
public DateTime RegistrationDate { get; set; }
var user = new OnlineShopUser { 
    UserName = Input.Email, 
    Email = Input.Email,
    Name = Input.Name,
    DOB = Input.DOB,
    Gender = Input.Gender,
    RegistrationDate = DateTime.Today
};


最後看一下結果,新增的欄位都補上了
( 註冊日期不用特別顯示欄位,它會自動把註冊當下的日期寫進去 )


上一篇
【從實作學習ASP.NET Core】Day14 | 後台 | 用 Identity 實作會員功能
下一篇
【從實作學習ASP.NET Core】Day16 | 後台 | 會員的角色
系列文
從實作學習ASP.NET Core - 30天的購物網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言