MVC5 網站開發之七 用戶功能 3用戶資料的修改和刪除

此次主要實現管理後臺界面用戶資料的修改和刪除,修改用戶資料和角色是常常用到的功能,但刪除用戶的狀況比較少,爲了功能的完整性仍是坐上了。主要用到兩個action 「Modify」和「Delete」。html

目錄json

MVC5網站開發之一 整體概述bootstrap

MVC5 網站開發之二 建立項目服務器

MVC5 網站開發之三 數據存儲層功能實現架構

MVC5 網站開發之四 業務邏輯層的架構和基本功能post

MVC5 網站開發之五 展現層架構網站

MVC5 網站開發之六 管理員 一、登陸、驗證和註銷this

MVC5 網站開發之六 管理員 二、添加、刪除、重置密碼、修改密碼、列表瀏覽spa

MVC5 網站開發之七 用戶功能 一、角色的後臺管理code

MVC5 網站開發之七 用戶功能 2 用戶添加和瀏覽

MVC5 網站開發之七 用戶功能 3用戶資料的修改和刪除

MVC5 網站開發之八 欄目功能 添加、修改和刪除

 

 

1、用戶資料修改(Modify)

此功能分兩個部分:

public ActionResult Modify(int id) 用於顯示用戶信息

[httppost]

public ActionResult Modify(FormCollection form)用戶就收前臺傳來的信息並修改

一、顯示用戶信息

/// <summary>
        /// 修改用戶信息
        /// </summary>
        /// <param name="id">用戶主鍵</param>
        /// <returns>分部視圖</returns>
        public ActionResult Modify(int id)
        {
            //角色列表
            var _roles = new RoleManager().FindList();
            List<SelectListItem> _listItems = new List<SelectListItem>(_roles.Count());
            foreach (var _role in _roles)
            {
                _listItems.Add(new SelectListItem() { Text = _role.Name, Value = _role.RoleID.ToString() });
            }
            ViewBag.Roles = _listItems;
            //角色列表結束
            return PartialView(userManager.Find(id));
        }

此action有一個參數id,接收傳入的用戶ID,在action中查詢角色信息,並利用viewBage傳遞到視圖,並經過return PartialView(userManager.Find(id))向視圖傳遞用戶模型返回分部視圖。

視圖代碼以下:

@model Ninesky.Core.User

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

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

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.RadioButtonFor(model => model.Sex, 1) 男
                @Html.RadioButtonFor(model => model.Sex, 0) 女
                @Html.RadioButtonFor(model => model.Sex, 2) 保密
                @Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

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

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

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

    </div>
}

二、修改用戶資料的後臺處理

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Modify(int id,FormCollection form)
        {
            Response _resp = new Auxiliary.Response();
            var _user = userManager.Find(id);
            if (TryUpdateModel(_user, new string[] { "RoleID", "Name", "Sex", "Email" }))
            {
                if (_user == null)
                {
                    _resp.Code = 0;
                    _resp.Message = "用戶不存在,可能已被刪除,請刷新後重試";
                }
                else
                {
                    if (_user.Password != form["Password"].ToString()) _user.Password = Security.SHA256(form["Password"].ToString());
                    _resp = userManager.Update(_user);
                }
            }
            else
            {
                _resp.Code = 0;
                _resp.Message = General.GetModelErrorString(ModelState);
            }
            return Json(_resp);
        }

此方法有兩個參數id 和FormCollection form,不用User直接作模型的緣由是由於user會把前臺全部數據都接收過來,這裏我並不想容許修改用戶名,因此在方法中使用TryUpdateModel綁定容許用戶修改的屬性。TryUpdateModel在綁定失敗時一樣會在在ModelState中記錄錯誤,能夠利用自定義方法GetModelErrorString獲取到錯誤信息並反饋給視圖。

二、前臺顯示和處理

打開Index視圖找到表格初始化方法,格式化列「Username」使其顯示一個鏈接,代碼紅線部分。

image

使其看起來這個樣子,當用戶點擊鏈接的時候能夠顯示修改對話框

image

彈出窗口和發送到服務器的js代碼寫到表格的onLoadSuccess方法裏

onLoadSuccess: function () {

                    //修改
                    $("a[data-method='Modify']").click(function () {
                        var id = $(this).attr("data-value");
                        var modifyDialog = new BootstrapDialog({
                            title: "<span class='glyphicon glyphicon-user'></span>修改用戶",
                            message: function (dialog) {
                                var $message = $('<div></div>');
                                var pageToLoad = dialog.getData('pageToLoad');
                                $message.load(pageToLoad);

                                return $message;
                            },
                            data: {
                                'pageToLoad': '@Url.Action("Modify")/' + id
                            },
                            buttons: [{
                                icon: "glyphicon glyphicon-plus",
                                label: "保存",
                                action: function (dialogItself) {
                                    $.post($("form").attr("action"), $("form").serializeArray(), function (data) {
                                        if (data.Code == 1) {
                                            BootstrapDialog.show({
                                                message: data.Message,
                                                buttons: [{
                                                    icon: "glyphicon glyphicon-ok",
                                                    label: "肯定",
                                                    action: function (dialogItself) {
                                                        $table.bootstrapTable("refresh");
                                                        dialogItself.close();
                                                        modifyDialog.close();
                                                    }
                                                }]

                                            });
                                        }
                                        else BootstrapDialog.alert(data.Message);
                                    }, "json");
                                    $("form").validate();
                                }
                            }, {
                                icon: "glyphicon glyphicon-remove",
                                label: "關閉",
                                action: function (dialogItself) {
                                    dialogItself.close();
                                }
                            }]
                        });
                        modifyDialog.open();
                    });
                    //修改結束
}

顯示效果以下圖

image

 

 

2、刪除用戶

UserController中添加刪除方法

/// <summary>
        /// 刪除
        /// </summary>
        /// <param name="id">用戶ID</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(int id)
        {
            return Json(userManager.Delete(id));
        }

 

打開Index視圖找到表格初始化方法,添加「操做」列格式化列使其顯示一個刪除按鈕,代碼紅框部分。

image

前臺顯示效果

image

而後在表格的onLoadSuccess方法裏剛寫的修改用戶信息的js代碼後面寫刪除用戶的js代碼

//修改結束

                    //刪除按鈕
                    $("a[data-method='Delete']").click(function () {
                        var id = $(this).attr("data-value");
                        BootstrapDialog.confirm("你肯定要刪除" + $(this).parent().parent().find("td").eq(3).text() + "嗎?\n 建議儘量不要刪除用戶。", function (result) {
                            if (result) {
                                $.post("@Url.Action("Delete", "User")", { id: id }, function (data) {
                                    if (data.Code == 1) {
                                        BootstrapDialog.show({
                                            message: "刪除用戶成功",
                                            buttons: [{
                                                icon: "glyphicon glyphicon-ok",
                                                label: "肯定",
                                                action: function (dialogItself) {
                                                    $table.bootstrapTable("refresh");
                                                    dialogItself.close();
                                                }
                                            }]

                                        });
                                    }
                                    else BootstrapDialog.alert(data.Message);
                                }, "json");
                            }
                        });
                    });
                    //刪除按鈕結束
                }
            });
            //表格結束

前臺顯示效果

image

 

==========================================

代碼下載請見http://www.cnblogs.com/mzwhj/p/5729848.html

相關文章
相關標籤/搜索