Roles and User management in asp.net webforms using code behind - c#

Issue: Using roles that I have created in my database, I want to be able to limit use for specific users depending on that users role.
Information: I am not using an MVC approach, only empty .aspx pages that I have wired up through to my database to show information etc. Provided are images of tables that are holding the role/user information in my database Roles , Users , Role/User. Ideally I want to remove items from my menu depending on which role the user is in. So lets say the user is in the role "Worker" they will only see 2 menu "controls" or "buttons" on the aspx page menu.
Attempted solution: On the landing page after a user has logged in, the Page_Load method checks to see which role the user is in and sends them to the appropriate page. The issue with this solution is that I have to create duplicates for every page depending on which role the user is in.
Question: How can I edit the HTML in a aspx webform using the c# code behind.
Question 2: Is there a simple solution to limit use depending on a user's role without have a ton of duplicate aspx pages.
Please let me know if there is more information needed.
The menu is created in the HTML on the aspx form like this:
<ul id="centered">
<li><a href='Welcome.aspx'><span>Home</span></a></li>
<li class='active has-sub'>
<a href='#'><span>Sales</span></a>
<ul>
<li class="active has-sub">
<a href='#'><span>Sales</span></a>
<ul>
<li><a href='Sales.aspx'><span>Create</span></a></li>
<li><a href='Sales.aspx'><span>View</span></a></li>
</ul>
</li>
</ul>
</li>

You need to mark you menu ul to runat="server" and give it a unique id.
<ul id="centered">
<li><a href='Welcome.aspx'><span>Home</span></a></li>
<li class='active has-sub'>
<a href='#'><span>Sales</span></a>
<ul>
<li class="active has-sub">
<a href='#'><span>Sales</span></a>
<ul runat="server" id="ul_menu">
<li><a href='Sales.aspx'><span>Create</span></a></li>
<li><a href='Sales.aspx'><span>View</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
Here I have change to <ul runat="server" id="ul_menu">
Now you can use this id ul_menu and add item to this from code behind on the basis of role of the user. for example --
protected void Page_Load(object sender, EventArgs e)
{
PopulateMenu();
}
private void PopulateMenu()
{
string role = "B";//You can get the role of logged in user from membeship
StringBuilder txt = new StringBuilder();
if (role == "A")
{
txt.Append("<li><a href='Sales.aspx'><span>Create</span></a></li>");
}
if (role == "B")
{
txt.Append("<li><a href='Sales.aspx'><span>View</span></a></li>");
}
ul_menu.InnerHtml = txt.ToString();
}

Related

Any way to check which View the user is on?

What I am trying to do is, add a button on my nav bar if the user is on a certain page (view).
I set my nav bar in my _Layout.cshtml
<ul class="nav navbar-nav">
<li><a asp-controller="Home" asp-action="Index" class="navbar-brand">bethany's Pie Shop</a></li>
<li><a asp-controller="Feedback" asp-action="Index">Feedback</a></li>
</ul>
So something like #IfUser is on Details view, add this list item.
Other answers don't seem to work in .netcore 2.0
In the Razor view, just access :
#this.Path
This will provide Something like :
~/Views/MailBox/Index.cshtml
If the code is in a layout file, to access the page, just write :
#this.ViewContext.View.Path
Then you can compare with a given view easily

Trying to call a variable using C# in HTML

I bet this question was asked before, but I couldn't find the right keywords to search for.
I am trying to call my variable (currentUser.FirstName) in the middle of the HTML, but it won't recognize the variable if I try. It does work if I don't put HTML tags around the code.
Here's my code:
<% var currentUser = ProjectGalaxy.Website.GetCurrentUser(); %>
<% if (currentUser != null)
{ %>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/pages/Dashboard.aspx">Welcome <%=
currentUser.FirstName %></a></li>
</ul>
<% } %>
Thank you,
Thomas
The variable you are creating within the first server block <%...%> is likely no longer in scope so when you exit the first server block and are writing the html you would have lost the context.
There are a couple of options depending if you are limited to addressing this in the display page only or are able to edit both the display and code behind.
Option 1. Remove the variable and refer to the underlying value from the server method directly.
There is a duplication of the call but it removes any scoping issues and keeps it localised if you are unable to edit the code behind.
<% if (ProjectGalaxy.Website.GetCurrentUser() != null) {%>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/pages/Dashboard.aspx">Welcome <%:ProjectGalaxy.Website.GetCurrentUser().FirstName%></a></li>
</ul>
<%}%>
Create a property in the code behind and assign the method value to that property. (Requires both display and code behind file changes)
// aspx.cs code behind
protected bool CurrentUser
{
get { return ProjectGalaxy.Website.GetCurrentUser(); }
}
// aspx display page
<% if (CurrentUser != null) {%>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/pages/Dashboard.aspx">Welcome <%:CurrentUser.FirstName%></a></li>
</ul>
<%}%>
Move control to the code behind and create an asp:panel server control with the code and toggle the visibility of the panel during the page lifecycle.
// aspx.cs code behind
pnlWelcomeMessage.Visible = true; // during page load if condition is true
// aspx display page
<asp:Panel ID="pnlWelcomeMessage" runat="server" CssClass="nav navbar-nav navbar-right" Visible="false">
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/pages/Dashboard.aspx">Welcome <%:ProjectGalaxy.Website.GetCurrentUser().FirstName%></a></li>
</ul>
</asp:Panel>
Hope it helps.

Checking if a user is logged in from site master file

When users log in, their sessions are set like so:
HttpContext.Current.Session["LoggedIn"] = true;
HttpContext.Current.Session["FullName"] = (string)Reader["FirstName"] + " " + (string)Reader["LastName"];
My Site.master file contains a navigation menu that's site-wide, and I'd like to change it to show different links depending on if the user is logged in or not.
Something like this in Site.master:
<div id="navigation">
<ul>
<%
if (HttpContext.Current.Session["LoggedIn"] != null)
{
%><li>Log out</li><%
}
else
{
%>
<li>Register</li>
<li>Log in</li>
<%
}
%>
</ul>
</div>
However, this doesn't seem to work. Looks like you can't use ASP tags like PHP tags.
How can I achieve this?
Seems like you are more in to PHP,For starters I recommend you go for the normal .NET process
1.Write HTML in aspx page,replace HTML 'a' with asp:linkbutton ,likr
<div id="navigation">
<ul>
<li><asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl="/user74/aspnet/Logout.aspx">Log out</asp:LinkButton></li>
</ul>
</div>
2.Write codes in pagename.aspx.cs page,in your case write session checks in page_load event
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.Session["LoggedIn"] != null)
{
LinkButton1.Visible = true;
}
}
In the first place, I would advice you to use ASP.NET Authentication to authenticate the users instead of using Session. This gives numerous benefits such as Role based security etc.
You can authenticate the users against
Windows (default)
Forms
Passport
Once you use one of these authentication methods, you can use the LoginView control to render different HTML for different set of users. For more information you can see ASP.NET Tip: Using the LoginView Control

how i can change the class of my <li> using javascript

My project is an asp.net and it has a master page that contains a list
<ul id="navigation">
<li id="li1" runat="server" class="selected">Events</li>
<li id="li2" runat="server">Add Event</li>
<li id="li3" runat="server">Profile</li>
<li id="li4" runat="server">Friends</li>
<li id="li5" runat="server">Find Friends</li>
<li id="li6" runat="server">Schedual</li>
<li>
<asp:LinkButton ID="LogOutButton" runat="server" OnClick="LogOutButton_Click">Log Out</asp:LinkButton>
</li>
</ul>
The selected class (css class) has a picture this picture tells the user on which page he is. How can I change this class using javascript or C# when I navigate?
I don't have a good experience with javascript
document.getElementById("li6").className = "whatever";
Should work/
$("#li1").addClass("selected");
Will work.
Example
This is very simply in JavaScript/jQuery.
But if this is for navigation, meaning it needs to be updated when you display a new page, I would do this in the markup from the server.
You didn't say much about how you are serving this page. But both ASP.NET WebForms and MVC allow you to control the HTML served in a number of different ways.
You can set for all your li tags classes like this for example:
<li class="li">
... content of the tag
</li>
and in your javascript you can add to all elements with class "li" some other class:
$(".li").addClass("classYouWantToAdd");
and in the css file:
.li
{
... needed css for the class
}
here is another post that tells you how to get elements by classname
Selecting a div by classname

How to customize the user control for only one page of the ASP.NET website?

I have two user controls (ascx); one contains some forms, and the other one contains the menu bar.
I used both of them in many pages. Now, I need to customize the one that has the menu bar for the Admin Homepage. So, is it possible to add some changes to the user control just for this page.
I mean by changes, adding two elements to the menu bar.
For instance, let us assume that the two pages are called: Admin, Settings. How will you customize the user control for them?
My code for the Menu User Control (ascx file):
<div class="topnav">
<ul class="menu" runat="server" >
<li>Home</li>
<li>Sub-Menu1
<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
</li>
<li>Sub-Menu2
<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item </li>
<li>Item</li>
<li>Item</li>
</ul>
</li>
<li>ITEM</li>
<li>About</li>
<li>Contact Us</li>
<li>Help</li>
<li class="menuItem1ToHide">Admin</li>
</ul>
<div class="clr"></div>
</div>
And inside the Master Page, I put:
<uc1:MenuBar ID="MenuBar1" runat="server" />
As you see from above code, I added the Admin page as the last element in the list, and the code-behind class, I added the bool method mentioned below, but I don't know how to make the last element only visible for the Admin rather than the other users
By the way, I am using the ASP.NET Role-Based Security since I am using the Windows Authentication. This to define the Admin from the Normal User.
Sure,
Add the two items to the menu bar, and hide them for everything but the admin page. You can do that in several ways; check the URL of the current request, or add a property to the user control (default the menu items to false).
public bool DisplayAdminOnlyMenuItems
{
get { return menuItem1ToHide.Visible; }
set
{
menuItem1ToHide.Visible = value;
menuItem2ToHide.Visible = value;
}
}
or you can use a method to do it. The property allows you to set it in markup or code. For instance, if your UC definition was this:
<uc:Menu ID="ucMenu" runat="server" />
You can set it, for the admin page, this way:
<uc:Menu ID="ucMenu" runat="server" DisplayAdminOnlyMenuItems="True" />
And then it will make those menu items visible.
EDIT: In your case, since everything is role security, add runat="server" to the LI to show or hide:
<li id="liAdmin" runat="server" class="menuItem1ToHide">Admin</li>
In your code, on prerender of the user control, do:
protected override void OnPreRender(EventArgs e)
{
liAdmin.Visible = this.User.IsInRole("Admin");
//if visible isn't available, use style["display"] = (this.User.IsInRole("Admin") ? "" : "none";
}
Something like that.
You could check the url in the Page_Load of the ascx and do the alterations there
Add the new elements to the user control and expose a property (say bool ShowAdminMenuItems) in the control. Show/hide the new elements based on this property's value. Set this property as true in the page where you need these two menu items to show up. Rest of the pages don't know about it, so they would not set it and the default value (false) would be in affect.
Yes, you can render some elements conditionally by doing:
<% if( somecondition) { %>
<li class="yourclass"> text here </li>
<%}%>

Categories

Resources