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


<<:  如何定期备份 MySQL 及删除旧有档案-适用 Windows

>>:  JS语法学习Day3

Notification

这篇练习一下推播,本来想要用这套 Local Notifications,结果出现一些错误。 上网查...

Flutter基础介绍与实作-Day28 旅游笔记的实作(9)

今天就继续来做剩下的两个地区吧! 一样先在assets资料夹内的View资料夹里建立南部和东部的资料...

【day13】连续上班日做便当2

今天的便当是无淀粉系列 主菜是鲜甜的肉束尾 其实我本人很害怕猪肉的腥味 但男友妈妈准备的食材都很好 ...

Day17 决策树实作

https://github.com/PacktPublishing/Machine-Learni...