C#MVC實現為雇員配置角色(完整詳細+資料庫)

来源:https://www.cnblogs.com/jnm121/archive/2020/01/12/12182573.html
-Advertisement-
Play Games

資料庫創建“用戶表”“角色表”“用戶角色關係表” create table roles ( RId int identity, RName varchar(50), Remark varchar(50) ) create table UserRole ( Users_UId int, roles_R ...


資料庫創建“用戶表”“角色表”“用戶角色關係表”

create table roles
(
RId int identity,
RName varchar(50),
Remark varchar(50)
)
create table UserRole
(
Users_UId int,
roles_Rid int
)
create table Users
(
UId int identity,
UName varchar(50),
UPwd varchar(50)
)

資料庫創建一個view視圖

create view USER_SHOW
AS
select RName,RId,UName,UId from Users join UserRole on Users.UId=UserRole.Users_UId join roles on UserRole.roles_Rid=roles.RId 

然後打開VS創建MVC

添加一個控制器

控制器需要引用

using Dapper;
using System.Data.SqlClient;

控制器代碼如下

public ActionResult Index()
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Unit13;Integrated Security=True"))
            {
                List<UserAndRole> list = conn.Query<UserAndRole>("select UId,UName,stuff((select ','+RName from USER_SHOW where a.UId = UId for xml path('')),1,1,'') as RName from USER_SHOW as a group by UId,UName").ToList();
                return View(list);
            }
        }

        // GET: User
        public ActionResult Shezhi(int Uid)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Unit13;Integrated Security=True"))
            {
                Session["Uid"] = Uid;
                ViewBag.list = GetBind();
                List<UserAndRole> list = conn.Query<UserAndRole>($"select RId,RName from Users join UserRole on Users.UId = UserRole.Users_UId join roles on UserRole.roles_Rid = roles.RId where UId = {Uid}").ToList();
                return View(list);
            }
        }
        public List<UserAndRole> GetBind()
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Unit13;Integrated Security=True"))
            {
                return conn.Query<UserAndRole>("select * from  roles ").ToList();
            }
        }

        public int Delete(int Rid)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Unit13;Integrated Security=True"))
            {
                return conn.Execute($"delete from UserRole where roles_Rid={Rid}");
            }
        }

        public int Add(string UId, string RId)
        {
            UId = Session["Uid"].ToString();
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Unit13;Integrated Security=True"))
            {
                object n = conn.ExecuteScalar($"select count(1) from UserRole where Users_UId={UId} and roles_Rid={RId}");
                if (Convert.ToInt32(n) == 0)
                {
                    return conn.Execute($"insert into UserRole values('{UId}','{RId}')");
                }
                else
                {
                    return 0;
                }

            }
        }

        public class UserAndRole
        {
            public int UId { get; set; }
            public string UName { get; set; }
            public string RName { get; set; }
            public int RId { get; set; }

        }

然後創建Index視圖(

  1. 頁面顯示雇員信息
  2. 點擊“設置角色”跳轉Shezi頁面為以下部分賦值

(1) 右側顯示的是所有“角色”

(2) 左側顯示的是當前雇員 現有的角色)

@using 配置角色.Controllers
@model List<UserController.UserAndRole>
@{
    ViewBag.Title = "Index";
}

<table class="table-bordered table">
    <tr>
        <td>編號</td>
        <td>雇員姓名</td>
        <td>角色</td>
        <td></td>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.UId</td>
            <td>@item.UName</td>
            <td>@item.RName</td>
            <td> <a href="/User/[email protected]">設置角色</a></td>
        </tr>
    }
</table>

運行效果

 

 

再添加一個Shezhi視圖

@{
    ViewBag.Title = "Shezhi";
}
@using 配置角色.Controllers
@model List<UserController.UserAndRole>

<div id="app" style="height:250px;width:100%;border:double">
    <div style="height:150px;width:250px;border:double;float:left;margin-top:45px;margin-left:20px">
        <span>所有可選角色:</span>
        <select id="Select1" multiple="true">
            @foreach (var item in ViewBag.list as List<UserController.UserAndRole>)
            {
                <option value="@item.RId">@item.RName</option>
            }

        </select>
    </div>
    <div style="height:150px;width:150px;float:left;margin-top:80px;margin-left:25%">
        <button onclick="Zuo()">←</button>
        <br>
        <button onclick="You()">→</button>
    </div>
    <div style="height:150px;width:250px;border:double;float:right;margin-top:45px;margin-right:20px">
        <span>當前雇員所屬角色:</span>
        <select id="Select2" multiple="true">
            @foreach (var item in Model)
            {
                <option value="@item.RId">@item.RName</option>
            }

        </select>

        <input id="Hidden1" type="@Session["Uid"]" />
    </div>
</div>

<script>
    function Zuo() {
        //alert(1);
        var id = $("#Select2").val();
        if (id == null) {
            alert('請選擇')
        }
        else {
            $.ajax({
                url: "/User/Delete?rid=" + id,
                success: function (d) {
                    if (d > 0) {
                        alert('成功');
                    }
                }

            })

        }

    }
    function You() {
        //alert(1);

        var UId = $("#Hidden1").val();
        var RId = $("#Select1").val();

        $.ajax({
            url: "/User/Add?Uid=" + UId + "&RId=" + RId,
            success: function (d) {
                if (d > 0) {
                    alert('成功');
                }
                else {
                    alert('用戶已存在');
                }
            }

        })
    }

</script>

實現效果

 

 

(1) 右側選擇了,再點擊中部的一個按鈕可以刪除

(2) 左側的選擇了,再點擊中部的另一個按鈕可以添加到左側

 


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

-Advertisement-
Play Games
更多相關文章
  • 2020年新年將至,先預祝.Net Core越來越好。 做了這麼多年一線開發,經常跟Http打交道。比如調用三方的Webservice,比如集成微信支付的時候服務端發起Prepay支付。特別是現在分散式、微服務大行其道,服務間通訊都離不開http調用。 多年前也造過幾個http client的小輪子 ...
  • await與async是C#5.0推出的新語法,關於await與async有很多文章講解。但看完後有沒有這樣一種感覺,感覺這東西像是不錯,但好像就是看不太懂,也不清楚該怎麼使用。雖然偶有接觸,但是一直都沒有真正搞明白。 我也是才剛剛摸索明白,把學習結果和大家探討一下看掌握得得對不對。 ...
  • 在資料庫工具類編寫的過程中,對事務的處理操作想避免各個原子操作的事務對象賦值重覆操作,想對外暴露的方法為如下形式 public bool ExecuteTransition(Action TransitionAction, out string ExceptionStr) 外部傳入的資料庫操作都使用 ...
  • 打開記事本編輯保存至.vbs 以管理員身份運行 Set obj = createobject("wscript.shell") obj.run ("reg add HKLM\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters ...
  • 我們希望將一個項目(dll)看做一個模塊/插件,一個模塊往往需要在應用啟動時做一些初始化工作,比如向IOC容器添加一些服務,為應用配置對象添加自己的數據源;也希望在應用關閉時做一些收尾工作,asp.net core為我們提供了這種機制,先來看看如何使用,再講講原理。 如何使用? 1、創建asp.ne ...
  • 1、線程池是單例的,全局唯一的,設置線程池最大活躍線程數是5,設置後,允許同時併發的Task只有5個,我們開啟100個task去做任務,從最後的輸出結果看到,雖然開啟了100個task,但是線程id始終是那5個如圖所示 2、結論:證明task是來源於線程池的,而且線程是重用的 ...
  • 一、前言 開始做了兩年web、期間也整了一段時間winform。後來做了兩年工控上位機,也就是做工控這兩年發現機器跟面向對象真是如此貼切,也是我從處理數據和流程的思維轉變為面向對象思維的開始。這對我後來學習mvc5、owin、.net core以及其它各種框架的學習有非常大的幫助,我發現我能看懂源碼 ...
  • 從C#6開始,只讀屬性可簡寫為表達式屬性。它使用雙箭頭替換了花括弧,get訪問器和return關鍵字。 例如: decimal CurrentPrice,sharedOwned; public decimal Worth { get{ return CurrentPrice*sharedOwned; ...
一周排行
    -Advertisement-
    Play Games
  • C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
  • 委托與事件 委托 委托的定義 委托是C#中的一種類型,用於存儲對方法的引用。它允許將方法作為參數傳遞給其他方法,實現回調、事件處理和動態調用等功能。通俗來講,就是委托包含方法的記憶體地址,方法匹配與委托相同的簽名,因此通過使用正確的參數類型來調用方法。 委托的特性 引用方法:委托允許存儲對方法的引用, ...
  • 前言 這幾天閑來沒事看看ABP vNext的文檔和源碼,關於關於依賴註入(屬性註入)這塊兒產生了興趣。 我們都知道。Volo.ABP 依賴註入容器使用了第三方組件Autofac實現的。有三種註入方式,構造函數註入和方法註入和屬性註入。 ABP的屬性註入原則參考如下: 這時候我就開始疑惑了,因為我知道 ...
  • C#TMS系統代碼-業務頁面ShippingNotice學習 學一個業務頁面,ok,領導開完會就被裁掉了,很突然啊,他收拾東西的時候我還以為他要旅游提前請假了,還在尋思為什麼回家連自己買的幾箱飲料都要叫跑腿帶走,怕被偷嗎?還好我在他開會之前拿了兩瓶芬達 感覺感覺前面的BaseCity差不太多,這邊的 ...
  • 概述:在C#中,通過`Expression`類、`AndAlso`和`OrElse`方法可組合兩個`Expression<Func<T, bool>>`,實現多條件動態查詢。通過創建表達式樹,可輕鬆構建複雜的查詢條件。 在C#中,可以使用AndAlso和OrElse方法組合兩個Expression< ...
  • 閑來無聊在我的Biwen.QuickApi中實現一下極簡的事件匯流排,其實代碼還是蠻簡單的,對於初學者可能有些幫助 就貼出來,有什麼不足的地方也歡迎板磚交流~ 首先定義一個事件約定的空介面 public interface IEvent{} 然後定義事件訂閱者介面 public interface I ...
  • 1. 案例 成某三甲醫預約系統, 該項目在2024年初進行上線測試,在正常運行了兩天後,業務系統報錯:The connection pool has been exhausted, either raise MaxPoolSize (currently 800) or Timeout (curren ...
  • 背景 我們有些工具在 Web 版中已經有了很好的實踐,而在 WPF 中重新開發也是一種費時費力的操作,那麼直接集成則是最省事省力的方法了。 思路解釋 為什麼要使用 WPF?莫問為什麼,老 C# 開發的堅持,另外因為 Windows 上已經裝了 Webview2/edge 整體打包比 electron ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...