Building a backend management system for ASP. Mvc4+ef5+easyui+unity2.x Injection (26)-Rights management system-assigning roles to users

Source: Internet
Author: User

Because you have previously assigned permissions to a role, you need to assign the role group to the user, and assign the user to a role group, a user can have multiple role groups, a role group contains multiple users, open module management, add an assigned opcode

And in

Role permission settings grant him

Add the following button to the index of Sysuser

@Html. Toolbutton ("Btnallot", "Icon-share", "Assigning roles", Perm, "Allot", True)

We want to pop up all the characters in the selection window to check and save. This everyone should think of, so first set up the view of the popup interface, I named Getrolebyuser
So add the following 3 methods to the Sysuser

  #region Set User Role [Supportfilter (ActionName = "Allot")] public actionresult Getrolebyuser (string userId)            {Viewbag.userid = UserId;            Viewbag.perm = Getpermission ();        return View ();        } [Supportfilter (ActionName = "Allot")] public jsonresult getrolelistbyuser (Gridpager Pager, string userId) {if (string.            Isnullorwhitespace (userId)) return Json (0);            var userlist = Userbll.getrolebyuserid (ref Pager,userid); var jsondata = new {total = pager.totalrows, rows = (from R                      In userlist Select New Sysrolemodel () {id= r.id, Name= r.name, Description = r.description, Flag = r.flag== "0"? " 0 ":" 1 ",}).            ToArray ()};        Return Json (Jsondata); }        #endregion [Supportfilter (actionname = "Save")] public jsonresult Updateuserrolebyuserid (string user            Id, String roleids) {string[] arr = roleids.split (', '); if (Userbll.updatesysrolesysuser (UserId, arr)) {Loghandler.writeservicelog (GetUserId (), "Ids:"                + Roleids, "success", "Assigning Roles", "User Settings");            Return Json (Jsonhandler.createmessage (1, suggestion.setsucceed), jsonrequestbehavior.allowget); } else {string errorcol = errors.                Error;                Loghandler.writeservicelog (GetUserId (), "Ids:" + Roleids, "Failed", "Assign Roles", "User Settings");            Return Json (jsonhandler.createmessage (0, Suggestion.setfail), jsonrequestbehavior.allowget); }                    }

Getrolebyuser for pop-up views

Getrolelistbyuser to get the role based on the selected user and to have the assigned role render the selection state (stored procedure implementation)

Use [Db]go/** * * * object:storedprocedure [dbo].    [P_sys_getrolebyuserid] Script date:02/21/2014 11:17:38 * * * * **/SET ansi_nulls ongoset quoted_identifier ongocreate proc [dbo]. [P_sys_getrolebyuserid] @UserId varchar ( -) asbegin--read the roles that the user containsSelectA.*,isnull (B.sysuserid,0) asFlag fromSysrole a LEFT join Sysrolesysuser B on a.ID=B.sysroleid and B.sysuserid=@UserId ORDER by B.sysuserid descend P_sys_getrolebyuserid
P_sys_getrolebyuseri

Updateuserrolebyuserid after the selection of the update (stored procedure implementation)

Create PROCEDURE [dbo]. [P_sys_updatesysrolesysuser] @roleId varchar (@userId varchar)as--  Update role User intermediate Relationship table begin    insert INTO Sysrolesysuser (Sysroleid,sysuserid)        values (@roleId, @userId) endp_sys_ Updatesysrolesysuser
P_sys_updatesysrolesysuser

The stored procedure statement is short, and if it's LINQ, it's not changeable, so I wrote the stored procedure.

You can refer to logic to make a program.

SYSBLL Add the following methods

Public iqueryable<p_sys_getrolebyuserid_result> Getrolebyuserid (ref Gridpager Pager, string userId)        {            iqueryable<p_sys_getrolebyuserid_result> querydata = Sysuserrepository.getrolebyuserid (db, userId);            Pager.totalrows = Querydata.count ();            Querydata = Sysuserrepository.getrolebyuserid (db, userId);            Return Querydata.skip ((pager.page-1) * pager.rows). Take (pager.rows);        }        public bool Updatesysrolesysuser (string userId, string[] roleids)        {            try            {                Sysuserrepository.updatesysrolesysuser (UserId, roleids);                return true;            }            catch (Exception ex)            {                exceptionhander.writeexception (ex);                return false;            }                    }

Sysrepository Add the following corresponding methods

        Public iqueryable<p_sys_getrolebyuserid_result> Getrolebyuserid (Dbcontainer db, String userId)        {            Return DB. P_sys_getrolebyuserid (userId). AsQueryable ();        }        public void Updatesysrolesysuser (String userId, string[] roleids)        {            using (dbcontainer db = new Dbcontainer ()) c7/>{                db. P_sys_deletesysrolesysuserbyuserid (userId);                foreach (String Roleid in Roleids)                {                    if (!string. Isnullorwhitespace (Roleid))                    {                        db. P_sys_updatesysrolesysuser (Roleid,userid);                    }                }                Db. SaveChanges ();            }        }

The DAL layer also uses a stored procedure to update the role User Intermediate Relationship table before deleting the association

Create PROCEDURE [dbo]. [P_sys_deletesysrolesysuserbyuserid] @userId varchar (as--) Update the Role User Intermediate Relationship table before deleting the association begin    Delete Sysrolesysuser where Sysuserid= @userIdEND

After you add the interface method to

Next fill in the Getrolebyuser View Code

@using app.admin, @using App.common, @using app.models.sys;@{viewbag.title="set user-included roles"; Layout="~/views/shared/_index_layoutedit.cshtml"; List<permModel> perm = (list<permmodel>) Viewbag.perm;if(Perm = =NULL) {Perm=NewList<permmodel>();}}<divclass="Mvctool BGB">@Html. Toolbutton ("Btnsave","Icon-save","Save", Perm,"Create",true)</div><divclass="pd3"><table id="userlist"></table></div>@*jqgrid*@<script type="Text/javascript">$ (function () {$ ('#UserList'). DataGrid ({URL:'/sysuser/[email protected] (Viewbag.userid)', Width:setgridwidthsub (6), Methord:'Post', Height:setgridheightsub ( A), Fitcolumns:true, Sortname:'Id', SortOrder:'desc', IDfield:'Id', PageSize: A, pagelist: [ A, -, -, +, -], pagination:true, Striped:true,//whether odd-even rows are differentiatedSingleselect:true,//single-selection modecolumns: [[{field:'Id', Title:'ID', Width: the, Hidden:true}, {field:'Name', Title:'Role Name', Width: -}, {field:'Description', Title:'Description', Width: the}, {field:'Flag', Title:'is assigned', Width: the, editor: {type:'checkbox', Options: {on:'1', off:'0'}}]], onloadsuccess:function () {varrows = $ ("#UserList"). DataGrid ("getRows");  for(vari =0; i < rows.length; i++) {                    //get the data for each row$('#UserList'). DataGrid ('BeginEdit', i);    }            }        }); });</script>@*operation*@<script type="Text/javascript">$ (function () {$ ("#btnSave"). Click (function () {varrows = $ ("#UserList"). DataGrid ("getRows");//This code is to get all the rows of the current page.             vardata =NewArray ();  for(vari =0; i < rows.length; i++) {                varSetflag = $ ("td[field= ' Flag '] input"). EQ (i). Prop ("checked"); if(Setflag)//determine if there is any modification{Data.push (rows[i].                ID); }            }            varRoleids =Data.join (); //Submit Database$.post ("/sysuser/updateuserrolebyuserid", {userId:'@ (Viewbag.userid)', Roleids:roleids}, function (data) {if(Data.type = =1) {window.parent.frameReturnByMes (data.message); Window.parent.frameReturnByReload (true); Window.parent.frameReturnByClose ()}Else{window.parent.frameReturnByMes (data.message); }             }, "JSON");    }); });</script>
View Code

Add the assigned JS Code at index

$ ("#btnAllot"). Click (function () {           var row = $ (' #List '). DataGrid (' getselected ');           if (row! = null) {                              $ ("#modalwindow"). HTML ("<iframe width= ' 100% '  height= ' 100% ' scrolling= ' auto ' frameborder = ' 0 ' src= '/sysuser/getrolebyuser?userid= "+ row. Id + "&iedate=" + getguid () + "></iframe>");               $ ("#modalwindow"). Window ({title: ' Assign Role ', width:720, height:400, iconcls: ' Icon-edit '}). Window (' open ');           else {$.messagebox5s (' hint ', ' @Suggestion. plasechoosetooperatingrecords ');}        });


Now you can display the interface.

Add a few more character tests.

To everyone to say, we do not ask me open source, will not release the source package, the source code is released to 14 (14 contains the material JS and other common elements), the database is 17, in the group to provide download, after the articles are posted code, and easy to understand, can be composed of my released system full version

Building a backend management system for ASP. Mvc4+ef5+easyui+unity2.x Injection (26)-Rights management system-assigning roles to users

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.