iT邦幫忙

2021 iThome 鐵人賽

DAY 16
1
Modern Web

ASP.NET Web Forms 入門 - 30天建立遊艇網頁專案後端及後台功能 C#系列 第 16

Day 16 - 依 NEWS 前台頁面分析拆解後,逐步建立後台功能 (上) - Calendar 日曆功能應用 - ASP.NET Web Forms C#

=x= 🌵 建立 News Manager - Content Page 後台頁面 - 日曆功能。


NEWS 前台頁面分析 :

https://ithelp.ithome.com.tw/upload/images/20210930/20139487m9NFwBOt3n.jpg

📌 從 NEWS 頁面點進頁面後,會見到新聞的列表頁,每個紅框都是一則新聞,每則新聞都會有綠框的"新聞縮圖"、橘框的"新聞發布日"、藍框的"新聞標題"可點連結、紫框的新聞"內文簡介",然後從新聞標題點進去後,可以見到完整的"新聞內容",新聞內容下方為"一連串的圖片",然後仔細看網址內容,尾段的網址傳值內容為"一組 GUID 隨機碼"用來識別是哪則新聞。

https://ithelp.ithome.com.tw/upload/images/20210930/20139487s5zVaR2E2p.jpg

  • 👀 GUID 維基百科介紹 : 全域唯一識別碼

  • 👀 GUID 微軟官網介紹 : Guid 結構

  • 🌵 微軟官網介紹 : GUID 是128位整數 (16 個位元組) 可在需要唯一識別碼的任何地方,在所有電腦和網路上使用。 這種識別碼的機率很低。



News Manager 後台頁面 - Calendar 日曆功能應用介紹 :

🧠 後台 Calendar 日曆功能應用內容如下 :

1. 選取日曆日期做為新聞發布日期。

2. 當天日期為預設選取。(下圖灰底為當天日期)

3. 有新聞內容的日期會有醒目標示。

4. 選取日期後可依日期加入新聞標題。(下圖藍底為選取日期)

5. 可勾選該則新聞是否有焦點提示。(為焦點新聞選取時會出現下圖黃底的特別提示)

6. 刪除新聞功能。

https://ithelp.ithome.com.tw/upload/images/20210930/201394877HC2iInZ1P.jpg



Calendar 日曆功能應用實作 :

1. 建立新聞資料表,發布日期的資料類型設為 date,表示不含時間,方便使用

https://ithelp.ithome.com.tw/upload/images/20210930/20139487OYpWRquYFh.jpg

  • 🌵 勾選是否為焦點的欄位預設值設為((0)),代表不去勾選時就認定不是焦點新聞。


2. 在 .aspx 頁配置 Calendar 控制項及相關配置參考如下

<h6>Date :</h6>
<asp:Calendar ID="Calendar1" runat="server" BackColor="White" BorderColor="White" BorderWidth="1px" Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="190px" NextPrevFormat="FullMonth" Width="100%" OnSelectionChanged="Calendar1_SelectionChanged" OnDayRender="Calendar1_DayRender">
    <DayHeaderStyle Font-Bold="True" Font-Size="8pt" />
    <NextPrevStyle Font-Bold="True" Font-Size="8pt" ForeColor="#333333" />
    <OtherMonthDayStyle ForeColor="#999999" />
    <SelectedDayStyle BackColor="#3399FF" ForeColor="White" Font-Bold="True" />
    <TitleStyle BackColor="White" BorderColor="#3399FF" BorderWidth="3px" Font-Bold="True" Font-Size="12pt" ForeColor="#3399FF" />
    <TodayDayStyle BackColor="#CCCCCC" />
</asp:Calendar>
<hr />
<h6>Headline : <asp:Label ID="LabIsTop" runat="server" Text="* Select item is top news !" ForeColor="Red" Visible="False" class="badge badge-pill badge-warning text-dark"></asp:Label></h6>
<asp:RadioButtonList ID="headlineRadioBtnList" runat="server" class="my-3" AutoPostBack="True" OnSelectedIndexChanged="headlineRadioBtnList_SelectedIndexChanged"></asp:RadioButtonList>
<asp:Button ID="deleteNewsBtn" runat="server" Text="Delete News" type="button" class="btn btn-danger btn-sm" OnClientClick="return confirm('Are you sure you want to delete?')" Visible="False" OnClick="deleteNewsBtn_Click" />
<hr />
<h6>Add Headline :</h6>
<asp:CheckBox ID="CBoxIsTop" runat="server" Text="Top Tag" Width="100%" />
<asp:TextBox ID="headlineTbox" runat="server" type="text" class="form-control" placeholder="Enter headline text" MaxLength="75"></asp:TextBox>
<asp:Button ID="AddHeadlineBtn" runat="server" Text="Add Headline" class="btn btn-outline-primary btn-block mt-3" OnClick="AddHeadlineBtn_Click"/>
  • 🌵 OnSelectionChanged 事件用於變更選取日期後讀取對應內容。

  • 🌵 OnDayRender 事件用於標示有新聞的日期於日曆上。


3. 在 .aspx.cs 後置程式碼 Page_Load 事件加入以下程式碼

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack) {
        Calendar1.SelectedDate = Calendar1.TodaysDate; //預設選取當日日期
        loadDayNewsHeadline();
    }
}


4. 先做加入新聞標題 Add Headline 按鈕的 OnClick 事件功能

protected void AddHeadlineBtn_Click(object sender, EventArgs e)
{
    //產生 GUID 隨機碼 + 時間2位秒數 (加強避免重複)
    DateTime nowTime = DateTime.Now;
    string nowSec = nowTime.ToString("ff");
    string guid = Guid.NewGuid().ToString().Trim()+ nowSec;
    //取得日曆選取日期
    string selNewsDate = Calendar1.SelectedDate.ToString("yyyy-M-dd");
    //取得是否勾選
    string isTop = CBoxIsTop.Checked.ToString(); //得到 "True" or "False"
    //將資料存入資料庫
    SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TayanaYachtConnectionString"].ConnectionString);
    string sql = "INSERT INTO News (dateTitle, headline, guid, isTop) VALUES (@selNewsDate, @headline, @guid, @isTop)";
    SqlCommand command = new SqlCommand(sql, connection);
    command.Parameters.AddWithValue("@selNewsDate", selNewsDate);
    command.Parameters.AddWithValue("@headline", headlineTbox.Text);
    command.Parameters.AddWithValue("@guid", guid);
    command.Parameters.AddWithValue("@isTop", isTop); //存入資料庫會轉為0或1
    connection.Open();
    command.ExecuteNonQuery();
    connection.Close();

    //渲染畫面
    headlineRadioBtnList.Items.Clear();
    loadDayNewsHeadline();

    //清空輸入欄位
    headlineTbox.Text = "";
}
  • 🌵 MSSQL 資料庫的 bit 資料類型,在編輯時是顯示 True / False,查詢時是顯示 0 / 1。


5. 建立 loadDayNewsHeadline(); 方法程式碼如下

private void loadDayNewsHeadline()
{
    //依選取日期取得資料庫新聞內容
    SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TayanaYachtConnectionString"].ConnectionString);
    string sql = "SELECT * FROM News WHERE dateTitle = @dateTitle ORDER BY id ASC";
    SqlCommand command = new SqlCommand(sql, connection);
    command.Parameters.AddWithValue("@dateTitle", Calendar1.SelectedDate.ToString("yyyy-M-dd"));
    connection.Open();
    SqlDataReader reader= command.ExecuteReader();
    while (reader.Read()) {
        string headlineStr = reader["headline"].ToString();
        string isTopStr = reader["isTop"].ToString();
        //渲染畫面
        LabIsTop.Visible = false;
        if (isTopStr.Equals("True")) {
            LabIsTop.Visible = true;
        }
        ListItem listItem = new ListItem();
        listItem.Text = headlineStr;
        listItem.Value = headlineStr;
        headlineRadioBtnList.Items.Add(listItem);
    }
    connection.Close();

    //預設選取新增新聞項目
    int RadioBtnCount = headlineRadioBtnList.Items.Count;
    if (RadioBtnCount > 0) {
        headlineRadioBtnList.Items[RadioBtnCount - 1].Selected = true;
        deleteNewsBtn.Visible = true;
    }
}
  • 🌵 可以使用 .Count 計算同一天有幾則新聞以及用 .Selected 來決定預設的選取項目。


6. 建立刪除新聞 Delete News 按鈕的 OnClick 事件功能

protected void deleteNewsBtn_Click(object sender, EventArgs e)
{
    //隱藏刪除鈕
    deleteNewsBtn.Visible = false;
    //取得選取項目內容
    string selHeadlineStr = headlineRadioBtnList.SelectedValue;
    //取得日曆選取日期
    string selNewsDate = Calendar1.SelectedDate.ToString("yyyy-M-dd");
    //連線資料庫
    SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TayanaYachtConnectionString"].ConnectionString);

    //刪除資料庫該筆資料
    string sqlDel = "DELETE FROM News WHERE dateTitle = @selNewsDate AND headline = @selHeadlineStr";
    SqlCommand commandDel = new SqlCommand(sqlDel, connection);
    commandDel.Parameters.AddWithValue("@selNewsDate", selNewsDate);
    commandDel.Parameters.AddWithValue("@selHeadlineStr", selHeadlineStr);
    connection.Open();
    commandDel.ExecuteNonQuery();
    connection.Close();

    //渲染畫面
    headlineRadioBtnList.Items.Clear();
    loadDayNewsHeadline();
}
  • 🌵 後續製作需加入刪除列表頁縮圖圖檔及刪除新聞內容組圖等功能。


7. 建立新聞標題選取項目按鈕選取改變時的 OnSelectedIndexChanged 事件功能

protected void headlineRadioBtnList_SelectedIndexChanged(object sender, EventArgs e)
{
    //依日期的新聞標題選取項目判斷是不是焦點新聞
    SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TayanaYachtConnectionString"].ConnectionString);
    string sql = "SELECT isTop FROM News WHERE dateTitle = @dateTitle AND headline = @headline";
    SqlCommand command = new SqlCommand(sql, connection);
    command.Parameters.AddWithValue("@dateTitle", Calendar1.SelectedDate.ToString("yyyy-M-dd"));
    command.Parameters.AddWithValue("@headline", headlineRadioBtnList.SelectedValue);
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    if (reader.Read()) {
        string isTopStr = reader["isTop"].ToString();
        //渲染畫面
        LabIsTop.Visible = false;
        if (isTopStr.Equals("True")) {
            LabIsTop.Visible = true;
        }
    }
    connection.Close();
}


8. 建立日曆日期選取改變時的 OnSelectionChanged 事件功能

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    deleteNewsBtn.Visible = false;
    LabIsTop.Visible = false;
    headlineRadioBtnList.Items.Clear();
    loadDayNewsHeadline();
}


9. 建立日曆日期渲染畫面時的 OnDayRender 事件功能

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    //取得新聞日期
    SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TayanaYachtConnectionString"].ConnectionString);
    string sql = $"SELECT dateTitle FROM News";
    SqlCommand command = new SqlCommand(sql, connection);
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read()) {
        //轉換為 DateTime 型別
        DateTime newsTime = DateTime.Parse(reader["dateTitle"].ToString());
        //有新聞的日期 且 此日期不是選中的日期時 就修改日期外觀
        if (e.Day.Date.Date == newsTime && e.Day.Date.Date != Calendar1.SelectedDate) {
            //渲染畫面
            //e.Cell.BorderWidth = Unit.Pixel(1); //外框線粗細
            //e.Cell.BorderColor = Color.BlueViolet; //外框線顏色
            e.Cell.Font.Underline = true; //有無下地線
            e.Cell.Font.Bold = true; //是否為粗體
            e.Cell.ForeColor = Color.DodgerBlue; //外觀色彩
        }
    }
    connection.Close();
}


本日總結 :

📢 今日的日曆功能實作,務必理解畫面元件間的互動,例如選取新聞標題時才會出現刪除鈕,切換日期時會先清掉標題項目再讀入,這些在明日會因為新增的內容有所關聯,而需要在今日實作內容的渲染畫面區域,增加更多控制項目去切換畫面內容,這些互動性間的理解,在明日實作其它功能做相關修改時,能更順利的去做操作。

  • 明日將介紹製作 News Manager - Content Page 後台的相關細節。

上一篇
Day 15 - 將 COMPANY 後台儲存資料提取後,送至 Certificat 前台渲染畫面 - 相簿資料渲染 - ASP.NET Web Forms C#
下一篇
Day 17- 依 NEWS 前台頁面分析拆解後,逐步建立後台功能 (下) - 畫面內容互動 - ASP.NET Web Forms C#
系列文
ASP.NET Web Forms 入門 - 30天建立遊艇網頁專案後端及後台功能 C#30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言