using Model; using System; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; public partial class admin_region_bed_bedstatus_create : MyWeb.config { private Model.ezEntities _db = new Model.ezEntities(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var code = Request.QueryString["code"]; if (!string.IsNullOrEmpty(code)) { LoadData(code); L_title.Text = "編輯區域類型"; } var categoryList = RegionRoomBedStatus.GetCategoryList(); TB_Category.DataSource = categoryList; TB_Category.DataTextField = "Text"; // 顯示文字 TB_Category.DataValueField = "Value"; // 選項值 TB_Category.DataBind(); TB_Category.Items.Insert(0, new ListItem("--請選擇分類--", "")); } } private void LoadData(string code) { var rt = _db.RegionRoomBedStatus.FirstOrDefault(r => r.Code == code); if (rt == null) { L_msg.Text = "
找不到資料
"; BTN_Save.Enabled = false; return; } HF_Code.Value = rt.Code; // ✅ 以 Code 為唯一識別 TB_Name.Text = rt.Name; TB_Code.Text = rt.Code; TB_Category.SelectedValue = rt.Category?.ToString(); Description.Text = rt.Description; } protected void BTN_Save_Click(object sender, EventArgs e) { try { RegionRoomBedStatus rt; var code = HF_Code.Value; // ✅ 用隱藏欄位的 Code 判斷 if (!string.IsNullOrEmpty(code)) { // 更新 rt = _db.RegionRoomBedStatus.FirstOrDefault(r => r.Code == code); if (rt == null) { L_msg.Text = "
資料不存在
"; return; } } else { // 新增 rt = new RegionRoomBedStatus(); rt.Code = TB_Code.Text.Trim(); // ✅ 以 Code 當主鍵 _db.RegionRoomBedStatus.Add(rt); } rt.Name = TB_Name.Text.Trim(); if (string.IsNullOrEmpty(rt.Name)) { L_msg.Text = "
名稱不能為空
"; return; } rt.Description = Description.Text.Trim(); if (int.TryParse(TB_Category.SelectedValue, out int category)) { rt.Category = category; } else { rt.Category = null; } _db.SaveChanges(); L_msg.Text = "
儲存成功
"; // ✅ 如果是新增,更新隱藏欄位並切換標題 if (string.IsNullOrEmpty(HF_Code.Value)) { HF_Code.Value = rt.Code; L_title.Text = "編輯區域類型"; } Response.Redirect("index.aspx"); } catch (Exception ex) { L_msg.Text = $"
錯誤:{ex.Message}
"; } } }