iT邦幫忙

2022 iThome 鐵人賽

DAY 25
0
Software Development

第一次學C#的經驗談系列 第 25

Day25主題:專案練習-關聯性作業的建立(下)

  • 分享至 

  • xImage
  •  

上一篇完成了[員工檔]的查詢及新增功能,接下來繼續來完成編輯及刪除的功能。

  1. Edit:就是編輯的頁面,程式碼有兩段;一段是後端帶出資料到前端,一段是前端傳遞資料到後端。
  • [EmployeeController]新增[Edit]程式碼。
/// <summary>
/// 員工編輯
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Edit(string id)
{
    //宣告回傳縣市列表
    List<Models.city> result1 = new List<Models.city>();
    //宣告回傳區域列表
    List<Models.area> result2 = new List<Models.area>();
    //宣告回傳薪資類別列表
    List<Models.salarytype> result3 = new List<Models.salarytype>();
    //使用Entities類別,名稱為db
    using (Models.HairSystemEntities db = new Models.HairSystemEntities())
    {
        //Linq方式取得Citys資料
        result1 = (from s in db.city select s).ToList();
        SelectList selectList1 = new SelectList(result1, "no", "name");
        ViewBag.CitySelectList = selectList1;

        //Linq方式取得Areas資料
        result2 = (from s in db.area select s).ToList();
        SelectList selectList2 = new SelectList(result2, "no", "name");
        ViewBag.AreaSelectList = selectList2;

        //Linq方式取得SalaryTypes資料
        result3 = (from s in db.salarytype select s).ToList();
        SelectList selectList3 = new SelectList(result3, "no", "name");
        ViewBag.SalaryTypeSelectList = selectList3;

        //性別選項
        ViewBag.SexSelectList = SexViewModel.SexDropDownList;

        //取得ID資料
        var result = (from s in db.employee where s.em_no == id select s).FirstOrDefault();
        //判斷是否有資料
        if (result != default(Models.employee))
        {
            return View(result);
        }
        else
        {
            TempData["resultMessage"] = "資料有誤,請重新操作!";
            return RedirectToAction("Index");
        }
    }
}

/// <summary>
/// 員工編輯,利用Entities回存資料庫
/// </summary>
/// <param name="postback"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Edit(Models.employee postback)
{
    if (this.ModelState.IsValid)
    {
        using (Models.HairSystemEntities db = new Models.HairSystemEntities())
        {
            //取得ID資料
            var result = (from s in db.employee where s.em_no == postback.em_no select s).FirstOrDefault();
            //儲存使用者變更資料
            result.em_no = postback.em_no;
            result.em_name = postback.em_name;
            result.em_id = postback.em_id;
            result.em_alias = postback.em_alias;
            result.em_sex = postback.em_sex;
            result.em_birthday = postback.em_birthday;
            result.em_tel = postback.em_tel;
            result.em_phone = postback.em_phone;
            result.em_city = postback.em_city;
            result.em_area = postback.em_area;
            result.em_address = postback.em_address;
            result.em_salarytype = postback.em_salarytype;
            result.em_rate1 = postback.em_rate1;
            result.em_rate2 = postback.em_rate2;
            result.em_remark = postback.em_remark;

            //儲存所有變更
            db.SaveChanges();

            //成功顯示訊息
            TempData["ResultMessage"] = string.Format("員工[{0}]成功編輯!", postback.em_name);
            //頁面轉至瀏覽頁
            return RedirectToAction("Index");
        }
    }
    else
    {
        //停留在Edit頁面
        return View(postback);
    }
}
  • 新增檢視頁面:在[View]上按右鍵 --> [新增檢視]
  • 完成的檢視畫面,一樣就稍為來調整一下,調它看起來專業一點;如果有特別注意的話,會發現跟[Create]內容差不多,所以就複製過來調整就行啦!
@model Hair.Models.employee

@{
    ViewBag.Title = "員工編輯";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<head>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
</head>

<h2>編輯員工</h2>

@if (ViewBag.ResultMessage != null) //判斷有訊息就顯示
{
    @Html.Label("info", (string)ViewBag.ResultMessage, new { @class = "text-info" })
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.em_no)

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.em_sex, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.em_sex, (IEnumerable<SelectListItem>)ViewBag.SexSelectList, "--請選擇性別--", new { @class = "form-control MakeWide btn btn-secondary dropdown-toggle" })
                @Html.ValidationMessageFor(model => model.em_sex, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.em_city, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.em_city, (SelectList)ViewBag.CitySelectList, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.em_city, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.em_area, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.em_area, (SelectList)ViewBag.AreaSelectList, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.em_area, "", new { @class = "text-danger" })
            </div>
        </div>

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

        <div class="form-group">
            @Html.LabelFor(model => model.em_salarytype, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.em_salarytype, (SelectList)ViewBag.SalaryTypeSelectList, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.em_salarytype, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.em_remark, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.em_remark, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.em_remark, "", 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>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    @Scripts.Render("~/bundles/datetimepicker")
    <script>
        //設定日期套件
        $('.datepicker').datetimepicker({
            format: 'YYYY/MM/DD',           //日期的顯示格式
            locale: moment.locale('zh-tw'), //國別
            daysOfWeekDisabled: [0, 6]      //隱藏的天數0為周日6為星期六
        });
        //填回原始日期內容
        $('#em_birthday').val('@(Model.em_birthday.HasValue ? Model.em_birthday.Value.ToString("yyyy/MM/dd") : "")');

        //設定縣市及區域連動關係
        $(document).ready(function () {
            DefaultCity();
            $('#em_city').change(function () { ChangeCity(); });
        });
        function SetAreaEmpty() {
            $('#em_area').empty();
        }
        function ChangeCity() {
            var selectedCityNo = $.trim($('#em_city option:selected').val());
            if (selectedCityNo.length == 0) {
                SetAreaEmpty();
            }
            else {
                $.getJSON("/Employee/GetArea", { CityNo: selectedCityNo }, function (data) {
                    $('#em_area').empty();
                    $.each(data, function (i, item) {
                        $('#em_area').append($('<option></option>').val(item.no).text(item.name));
                    });
                });
            }
        }
        function DefaultCity() {
            var selectedCityNo = $.trim($('#em_city option:selected').val());
            if (selectedCityNo.length == 0) {
                SetAreaEmpty();
            }
            else {
                $.getJSON("/Employee/GetArea", { CityNo: selectedCityNo }, function (data) {
                    $('#em_area').empty();
                    $.each(data, function (i, item) {
                        $('#em_area').append($('<option></option>').val(item.no).text(item.name));
                    });
                    //填回原始區域內容
                    $('#em_area').val('@Model.em_area');
                });
            }
        }
    </script>
}
  1. Del:就是刪除的動作,只有程式碼沒有檢視頁面。
  • [EmployeeController]新增[Del]程式碼。
/// <summary>
/// 刪除員工
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Delete(string id)
{
    using (Models.HairSystemEntities db = new Models.HairSystemEntities())
    {
        //取得ID資料
        var result = (from s in db.employee where s.em_no == id select s).FirstOrDefault();
        //判斷是否有資料
        if (result != default(Models.employee))
        {
            //刪除所選資料
            db.employee.Remove(result);
            //儲存所有變更
            db.SaveChanges();

            //成功顯示訊息
            TempData["ResultMessage"] = string.Format("員工[{0}]成功刪除!", result.em_name);
            //頁面轉至瀏覽頁
            return RedirectToAction("Index");
        }
        else
        {
            TempData["resultMessage"] = "資料不存在,請重新操作!";
            return RedirectToAction("Index");
        }
    }
}
  • 完成後,在[Controllers][Views] --> [City]內分別會產出相關程式作業。
    https://ithelp.ithome.com.tw/upload/images/20220925/20142779BF2ZwFRdsB.png

比較複雜的功能作業也完成囉~~
類似的作業,也讓大家自行練習練習吧!!


上一篇
Day24主題:專案練習-關聯性作業的建立(上)
下一篇
Day26主題:專案練習-查詢作業的建立
系列文
第一次學C#的經驗談30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言