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

来源:http://www.cnblogs.com/mzwhj/archive/2016/08/05/5741267.html
-Advertisement-
Play Games

這次主要實現管理後臺界面用戶資料的修改和刪除,修改用戶資料和角色是經常用到的功能,但刪除用戶的情況比較少,為了功能的完整性還是坐上了。主要用到兩個action “Modify”和“Delete”。 目錄 MVC5網站開發之一 總體概述 MVC5 網站開發之二 創建項目 MVC5 網站開發之三 數據存 ...


這次主要實現管理後臺界面用戶資料的修改和刪除,修改用戶資料和角色是經常用到的功能,但刪除用戶的情況比較少,為了功能的完整性還是坐上了。主要用到兩個action “Modify”和“Delete”。

目錄

MVC5網站開發之一 總體概述

MVC5 網站開發之二 創建項目

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

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

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

MVC5 網站開發之六 管理員 1、登錄、驗證和註銷

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

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

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

 

 

一、用戶資料修改(Modify)

此功能分兩個部分:

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

[httppost]

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

1、顯示用戶信息

/// <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>
}

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

[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獲取到錯誤信息並反饋給視圖。

2、前臺顯示和處理

打開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

 

 

二、刪除用戶

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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 鏈接:http://pan.baidu.com/s/1eS4rR9o 密碼:0uws 手機電腦全套破解的教程正在重新打包,很快就可以了! ...
  • 前言: 此方法只能借鑒,如果網友安裝失敗,後果自負。 借鑒的書籍《跟老男孩學Linux運維 Web集群實戰》 文章所使用的Mysql:https://yunpan.cn/Oc6RkgKRFVUvex 訪問密碼 0000 其他軟體下載:http://mirror.bit.edu.cn/mysql/Do ...
  • 回到目錄 我們知道在Linq里的分組groupby可以對集合中一個或者多個欄位進行分組,並對其中一個屬性進行聚合,而Linq為我們提供了多種聚合方法,由aver,sum,count等,而在大叔許可權體系中,以上幾種聚合是不夠的,因為我們需要對許可權欄位進行按位聚合,或者說對它進行按位的或運算,這對於學過 ...
  • 程式的本質是數據加演算法。通俗一點來說呢,其實就是用戶給一個輸入,經過演算法的處理之後,電腦反饋一個輸出給用戶。可以很清楚的看出,在這個過程中,處於主導地位的是數據。但是,當我們在進行圖形用戶界面(Graphic User Interface,GUI)編程的時,數據總是處於被動地位。也就是說,程式總是 ...
  • 背景 前段時間公司有個需求(每天給業務導出一批數據,以excel的形式通過郵件發送給他)。A說:直接寫個服務,判斷等於某個時間點,執行一下sql語句,生成excel,寫個EmaiHelper發送給他不就得了,這有什麼麻煩的?B說:我了個親娘來,還寫服務呢?你還需要搞個timer去判斷時間點?多費勁啊 ...
  • 博客園有很多人發表了他們自己認為的框架,好奇,就點進去看了下。 我只想說那真的稱不上是框架。 我建議他們可以多多看.net的是如何設計的、一些第三方框架的代碼是如何寫的。拿熟悉的.net web框架的來說,從:using System; 到:using System.Web;再到:using Sys ...
  • VS2013自帶IIS Express,無法發佈JSON文件,需添加MIME映射。 沒有圖形界面,只能命令行。 進入C:\Program Files(x86)\IIS Express文件夾,輸入:appcmd set config /section:staticContent /+[fileExte... ...
  • 可能對於初入此行業人來說有些困惑,實現起來有一絲複雜。 比如說時間是:2016-08-05 14:46:30,中間過了56秒鐘。要求得出56秒之後的時間格式是:年月日時分秒 下麵介紹最簡單的辦法, 也就是直接用 2016-08-05 14:46:30.AddSeconds(56)即可。 其中的Add ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...