iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
自我挑戰組

C# 學習之旅系列 第 23

ASP.NET MVC 從入門到放棄(Day23)-MVC編輯資料介紹

接下來講講編輯 部分...

在查詢的View那邊可以看到下方程式碼

@Html.ActionLink("編輯", "Edit", new { categoryID = md.CategoryID }, new { @class = "glyphicon glyphicon-pencil" })

註解:如果要傳參數過去Action 可以加上 new { categoryID = md.CategoryID }

另外講個小技巧當不知道該Action要填入什麼值其實可以把滑鼠放在程式碼上方如下圖就可以知道要填什麼參數了
https://ithelp.ithome.com.tw/upload/images/20210909/20140001gU596g45AB.png

初始 顯示進入類別編輯Controller

public ActionResult Edit(string categoryID)
{
  try
  {
     var result = new Category().Get_Edit_Category(categoryID);
     if (result != default(Category))
     {
        return View(result);
     }
     else
     {   //如果沒有資料則顯示錯誤訊息並導回Index頁面
        TempData["resultMessage"] = "資料有誤,請重新操作";
        return RedirectToAction("Index", "Category");
     }
   }
   catch (Exception e)
   {
      ViewBag.ResultMessage = e.ToString();               
      return View();
    }
}

1.Edit(string categoryID) 傳進來的參數就是從@Html.ActionLink new { categoryID = md.CategoryID } 過來的
2.Get_Edit_Category(categoryID) 為取得類別相關資訊

類別 Model模板

public class Category
{

        [Required]
        [Display(Name = "類別編號")]
        [StringLength(4, ErrorMessage = "{0}的長度至少必須為{2}的字元。", MinimumLength = 1)]
        public string CategoryID { get; set; }

        [Display(Name = "類別名稱")]
        [StringLength(20, ErrorMessage = "{0}的長度至少必須為{2}的字元。", MinimumLength = 1)]
        public string CategoryName { get; set; }

        public Category()
        {

        }
        
        public Category Get_Edit_Category(string categoryID)
        {
            var result = new Category();

            using (var conn = new MySqlConnection(GlobalFunction.GlobalConnString))
            {

                conn.Open();

                using (var command = conn.CreateCommand())
                {
                    command.CommandText = "SELECT Category, Category_Name FROM Category WHERE Category = @Category ";
                    command.Parameters.AddWithValue("@Category", categoryID);

                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {

                            while (reader.Read())
                            {
                                result = new Category()
                                {
                                    CategoryID = (string)reader["Category"],
                                    CategoryName = (reader.IsDBNull(reader.GetOrdinal("Category_Name"))) ? "" : (string)reader["Category_Name"]
                                };
                            }

                            return result;
                        }
                        else
                        {
                            return result;
                        }
                    }
                }
            }
        }
        
public bool Patch_Category(Category category, string InputUserID)
{
            var result = false;
            using (var conn = new MySqlConnection(GlobalFunction.GlobalConnString))
            {
                conn.Open();

                using (var command = conn.CreateCommand())
                {
                    command.CommandText = "Update Category Set Category_Name = @Category_Name ,ModifyEID =@ModifyEID,ModifyDate = Now() Where Category = @Category ;
                    command.Parameters.AddWithValue("@Category", category.CategoryID);
                    command.Parameters.AddWithValue("@Category_Name", category.CategoryName);
                    command.Parameters.AddWithValue("@ModifyEID", InputUserID);
                    command.ExecuteNonQuery();

                    result = true;
                    return result;
                }
            }
        }        
}

Edit View

@model WebApplication1.Models.Category.Category

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout2.cshtml";
}

@if (ViewBag.ResultMessage != null)//判斷如果有訊息,則顯示。
{
    //@Html.Label("info", (string)ViewBag.ResultMessage, new { @class = "text-info" })
    <script type="text/javascript">
            var message = @Html.Raw(Json.Encode(ViewBag.ResultMessage));
            alert(message);
    </script>
}

@using (Html.BeginForm("Edit", "Category", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <br> </br>
        <h2>類別資料修改作業</h2>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.CategoryID)


        <div class="form-group">
            @Html.LabelFor(model => model.CategoryID, htmlAttributes: new { @class = "control-label col-md-1" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CategoryID, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly" } })
                @Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CategoryName, htmlAttributes: new { @class = "control-label col-md-1" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CategoryName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CategoryName, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="存檔" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("返回清單", "Index")
</div>

1.@readonly = "readonly" 唯讀的意思
2.disabled = "disabled" 輸入視窗反灰
3.@model WebApplication1.Models.Category.Category 因為只是傳一筆類別Mode資料過來所以不會像查詢頁面會有IEnumerable(集合)

類別表單送出 Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Category postback)
{
   try
   {
   
   if (this.ModelState.IsValid)
   {
   var result = new Category().Patch_Category(postback,(string)Session["UserID"]);
      if (result){
        TempData["ResultMessage"] = String.Format("會員[{0}]成功編輯", postback.CategoryID);
        return RedirectToAction("Index", "Category");
      }
     else
      {
          ViewBag.ResultMessage = "資料有誤,請檢查";            
          return View(postback);
      }

   }
   else
   {
      ViewBag.ResultMessage = "資料有誤,請檢查";
      return View(postback);
    }
   }
   catch (Exception e)
  {
     ViewBag.ResultMessage = e.ToString();
     return View();
  }
}

1.this.ModelState.IsValid 驗證功能 後續會講
2.Patch_Category 更新類別資料funtion


上一篇
ASP.NET MVC 從入門到放棄(Day22)-MVC新增資料介紹
下一篇
ASP.NET MVC 從入門到放棄(Day24)-MVC刪除資料介紹
系列文
C# 學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言