MVC Web site Development Rights Management Chapter _ Practical Skills

Source: Internet
Author: User

First, the preface

Just arrived at the company did not have much time to start to contact with MVC to now can not say understand, can only say to reach will use this level, feel MVC used to write the web is still very powerful, clear hierarchy.

Today I write about the rights management of this piece, the right to feel the site is mainly divided into menu permissions and role permissions, first of all, to say role permissions, relatively simple different roles can see different pages this is the role of permissions, menu permissions can also be said to operate permissions, is specific to a button, or permission to view or use a drop-down box.

Second, role permissions

1. User Roles

First, the role of permissions, each user has a variety of different roles, a one-to-many relationship.

2. Menu Management

In the menu management we can manage, a menu, that role can be seen on the tick is easier to control.

3. The database

Then look at the database, the table of roles and the user-role relationship table.

Then the relationship table of roles and menus, where the Permissionids field is separated by the action permission.

4. User Login

When the user log in we can according to the ID of the login to all of his characters to save to the session, and according to the login to find the appropriate menu.

/role basic information sqlhelperparameter sqlhelperparameterrole = new Sqlhelperparameter (); Sqlhelperparameterrole.add ("UserId", dtuserrow["UserId").
   ToString ()); DataTable dtrole = sqlhelper.executedatatable (@ "Select Sys_roles.roleid, Sys_roles.rolename, Sys_roles.weigh T from (select Userid,roleid to sys_usersinroles where UserId = @UserId) as a left join Sys_roles on a.
   Roleid = Sys_roles.roleid ", sqlhelperparameterrole);
   int dtrolecount = DtRole.Rows.Count; Roleweightmax = Int.
   MaxValue;
    for (int i = 0; i < Dtrolecount i++) {rolessession rs = new rolessession (); Rs. Roleid = Guid.parse (dtrole.rows[i]["Roleid").
    ToString ()); Rs. RoleName = dtrole.rows[i]["RoleName"].
    ToString (); Rs.
    Weight = Convert.ToInt32 (dtrole.rows[i]["Weight")); if (Roleweightmax > Rs. Weight) {Roleweightmax = rs.
    Weight;
   } rolelist.add (RS); }
public class Rolessession
 {public
  Guid Roleid {get; set;}
  public string RoleName {get; set;}
  Weight public
  int Weight {get; set;}
 }

Foreground code:

 <div data-options= "region: ' West ', split:true" title= "navigation menu" style= "width:200px; padding1:1px;
 Overflow:hidden "id=" Left_nav "> <div class=" easyui-accordion "data-options=" Fit:true,border:false "
 >
  @H9C. Pms. Bll. LogOn.MenuList.GetMenu (viewbag.username)
 </div>
</div>

Controller:

public static mvchtmlstring GetMenu (String userName) {Menu menu = new Menu (); Menustructure ms = Menu.
   Getmenuliststructure (UserName); if (MS!= null) {Ms. Children.remove (Ms.
   Children.firstordefault (o => o.modelcode = = "0" && O.parentid = = "0"));
  Return to New Mvchtmlstring (Menunav ("0", ms));  private static string Menunav (String menucode, Menustructure Menustruc) {if (Menustruc = null) {return
   "<div> no menu available </div>"; } list<menustructure> List = MenuStruc.Children.Where (m => m.parentid = = Menucode).
   ToList ();

   StringBuilder Sbmenu = new StringBuilder (); foreach (var item in list) {if (item). ParentID = = "0") {sbmenu.append ("<div title=\" + item.)
     Title + "\" "Style=\" overflow:auto;\ ">"); Sbmenu.append ("<ul id=\" menu + item.)
     ParentID + "class=\" easyui-tree\ "animate=\" true\ "dnd=\" true\ ">");

    Sbmenu.append ("<li>"); else {sbmenu.append ("&Lt;ul id=\ "Menu" + Item.
     ParentID + "class=\" easyui-tree\ "animate=\" true\ "dnd=\" true\ ">"); if (item.
     Children.Count = = 0) {sbmenu.append ("<li>");
     else {sbmenu.append ("<li state=\" closed\ ">");

    } sbmenu.append ("<span>"); if (item. URL = = "/") {sbmenu.append ("<a class=\" e-submenu\ "href=\" javascript:void (0); \ "Title=\" "+ Item.
    Title + ">");
     else {string Tabsicon = "14"; if (!string. Isnullorwhitespace (item. Icon)) {Tabsicon = Item. Icon.replace ("/content/images/", "").
     Replace (". png", ""); } sbmenu.append ("<a class=\" e-submenu\ "href=\" #\ "onclick=\" AddTab ("" + Item). Url + "', '" + Item.
     Title + "') \ >"); Sbmenu.append ("</span>"); if (isexistparent (item). Modelcode, Item) {Sbmenu.append (Menunav) (item.Modelcode, item));
    } sbmenu.append ("</li>");


    Sbmenu.append ("</ul>"); if (item.
    ParentID = = "0") {sbmenu.append ("</div>");
  } return sbmenu.tostring (); } private static bool Isexistparent (string modelcode, Menustructure menumodels) {var query = Menumodels.children.
   FirstOrDefault (m => m.parentid = = Modelcode);
   if (query = = NULL) {return false;
  return true;

 }

Menu class:

public class Menustructure
 {public
  string Modelcode;
  public string Title;
  public string Icon;
  public string Url;
  public string ParentID;
  Public list<menustructure> Children = new list<menustructure> ();
 }

where the Getmenuliststructure () method is based on the user name to get menu list structure, my username here is unique in the database, here to pay attention to a bit more troublesome is based on the class can see that the menu has a parent menu submenu, so the method needs to have two loops to add.

Third, menu permissions
that is, operation permissions, such as the operation of a button. First of all, we put all the operation permissions on the button into a class, (there is a better way to recommend to me, thank you)

Menus
 {
  public static int gongdan = 503000000;//task Order
 } 

Then we need to manipulate the buttons on the page where the button is located in the Controllers (loading page) to save in the ViewBag, as follows:

 public ActionResult Index () {h9c. Pms. Bll. Rbac. Permission pm = new BLL. Rbac.
Permission (); Viewbag.isreportplan = pm. Isrolehavepermissions (Roles.shigongduizhang, Menus.gongdan, base. Usersessionmodel, Menus.gongdanreportplanbyshigongteamer);
  Report the Construction Plan return View (); }

///<summary>///Determines whether a permission is in the list that obtains a role's permissions///</summary>///<param N Ame= "Roleid" ></param>///<param name= "Modelcode" ></param>///<param "Name=" Usersessionmodel  "></param>///<param name=" Permissioncode "></param>///<returns></returns> Public BOOL Isrolehavepermissions (Guid roleid, int modelcode, Usersessionmodel usersessionmodel, int permissioncode) {List <PermissionModel> permissionmodellist = this.
   Getrolepermissionlist (Roleid, Modelcode, Usersessionmodel);
   if (permissionmodellist = = null) {return false;
    foreach (Var o in permissionmodellist) {if (O.pcode = = Permissioncode) {return true;
  return false; }

///<summary>///get a list of role permissions///</summary>///<param name= Id "></param>///<param name=" Modelcode "></param>///<param name=" Usersessionmodel ">< /param>///<returns></returns> public list<permissionmodel> getrolepermissionlist (Guid Roleid, int Modelcode, Usersessionmodel usersessionmodel) {foreach (var o in usersessionmodel.rolelist) {if (O.rolei D = = Roleid) {list<model.rbac.permissionmodel> permissionlist = this.
     Permissionlist (Roleid, Modelcode);
    return permissionlist;
  } return null; }

<summary>///Get permissions under a certain role in a menu///</summary>///<param name= "ModelID" ></param>///&L T;param name= "MenuID" ></param>///<returns></returns> public list<permissionmodel>
   Permissionlist (Guid roleid, int menuid) {list<permissionmodel> pmlist = new list<permissionmodel> (); using (rbaccontext CONNEF = new Rbaccontext ()) {Sys_role_model_permissions SRMP = Connef.sys_role_model_permissio Ns.
    FirstOrDefault (o => o.modelid = = MenuID && O.roleid = Roleid); if (SRMP!= null) {string permissions = Srmp.
     Permissionids; if (!string. Isnullorwhitespace (permissions)) {string[] PIDs = permissions.
      Split (new char[] {' | '}); for (int i = 0; i < PIDs. Length; i++) {if (!string). Isnullorwhitespace (Pids[i])) {Pmlist.add (new Permissionmodel () {Modelcode = MenuID, PCo
    de = Convert.ToInt32 (Pids[i]), pname = ""    });
  }}} return pmlist;

 }

The last method applies to the ability of the EF to get a menu and a role
The front desk is very simple:

@if (Viewbag.isreportplan = = True)
  {
   @:
    <a href= "#" class= "
     Easyui-linkbutton l-btn" iconcls= " Icon-add "> button </a> 
  } 

Iv. the end of the

To sum up, the first is to have a menu management module, it can not only manage the menu can also manage the permissions in the menu and each role on the menu, and then the control of the background, the above permissions model in the weight, refers to each role has a weight, each user has his maximum weight, According to this weight we can do a lot of conditions of control, simply say also for convenience.
The first technical document, writing also need more exercise, later try to write more blog, not write the document of the Code farmers are not good programmers.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.