In my app I have 3 dropdowns in the NeBar menu with the menu
Access is restricted, but the menu is visible to everyone. I want to hide unnecessary elements for general and public (any other) users.
I'm using the windows login names for identification
I ask the database to get a user role And if the user is a normal user or administrator, then ask for the inquiry.
My solution:
public bool CheckIfAdmin {string login} {bool admin = false; EquipmentEntities DB = new tool (); Tupal & lt; String, string & gt; Credentials = GateName (login); Integer role-id = db.Users.Where (w = & gt; w.Name == credentials.Item1). Where (w = & gt; w.Surname == credentials.Item2) .Select (s =) S.RoleId). FirstOrDefault (); If (RoleId == 1) {admin = true; } Return Manager; }
and about a single code to check whether the user
contains methods:
if (CheckIfAdmin (login) ) {ViewBag .Role = 1; } And if (checkfusor (login)) {ViewBag.Role = 2; }
and finally in the layout:
@if (ViewBag.Role == 1) {& lt; Li class = "dropdown" & gt; & Lt; A href = "#" class = "drop-toggle" data-toggle = "dropdown" & gt; Admin & lt; P class = "carat" & gt; & Lt; / P & gt; & Lt; / A & gt; & Lt; Ul class = "dropdown menu" & gt; // menu & lt; / Ul & gt; & Lt; / Li & gt; }
and I want to hide almost the same code for the second dropdown. It is working but at this time I need to examine the role in every method. Can someone suggest me a big amount of unnecessary code, how to do it better?
I see that your role is stable, code> if (RoleId == 1) So that I am a user administrator, I think that you can define roles like enum
.
public enum UserRole {user = 1, manager = 2, administrator = 3, //SuperAdmin..etc. }
Create a base controller, add current user property and execute the action when the current user takes
public class BaseController: Controller {Protected Override Zero OnActionExecuting (ActionExecutingContext) FilterContext) {CurrentUser = db.GetLoggedUserFromDatabase () ;. // ViewBag.CurrentUser = CurrentUser to use in the controller; // to use in ideas) the public user receives {current; Set; }}
Finally apply your controller BaseController
:
public class AnyController: BaseController {// In every action you present User's Details // You already know the current user role you can use it. For example: public ActionResult AnyAction () {if (! CurrentUser = Null) // Logs user, {ifUser (CurrentUser.Role == (int) UserRole.Admin) {// user administrator}}} }
In such ideas, you can use ViewBag.CurrentUser
. First cast it and check the role as the controller.
Comments
Post a Comment