Reputation: 10164
I am trying to hide html elements from plain users such that only users. I have simple asp.net web form setup that makes use of roles provider and membership.
<li runat="server" id="li1" visible ='<%# HttpContext.Current.User.IsInRole("admin") %>'><a href="screeners.aspx"><span> Admin link</span></a></li>
I also am trying this without success:
<li runat="server" id="liAdminUsers" visible ='<%# isAdmin %>'><a href="screeners.aspx"><span> The Hopper</span></a></li>
the code behind is:
public bool isAdmin =false;
protected void Page_Load(object sender, EventArgs e)
{
isAdmin = Page.User.IsInRole("admin");
}
update: I know I can get it working by adding in the code behind:
liAdminUsers.Visible = false ;
but want a UI solution in the .aspx code
Upvotes: 0
Views: 1884
Reputation: 2943
I had a similar issue earlier and I solved it by declaring a protected variable in .aspx.cs file and directly using it in the aspx page.
Aspx Page:
<li runat="server" id="li1" visible ='<%# IsAdmin %>'>
<a href="screeners.aspx"><span> Admin link</span></a>
</li>
Aspx.cs File:
protected bool IsAdmin = false;
Upvotes: 0
Reputation: 167
in aspx files you can try :
<% if (isAdmin()==true ) { %>
your html codes and server controlls
<%}>
if isAdmin retruns true asp write yours codes in (your html codes and server controlls) your page.
Upvotes: -1
Reputation: 394
If you are reaching a variable from code behind, you need to use <%= isAdmin%> , not <%# isAdmin()%>
Upvotes: 0
Reputation: 547
I suggest you formulate a class that will hide the said elements.
CSS
hide-elements {
display:none;
}
show-elements {
display:block;
}
C# CodeBehind
public string isAdmin()
{
if (condition == false)
return "hidden-elements";
else
return "show-elements";
}
HTML code
<li runat="server" id="liAdminUsers" class='<%# isAdmin() %>'>.....</li>
Hope this help. :D (my first post)
Upvotes: 0
Reputation: 124794
You are using data-binding syntax <%# ... %>
, so you need to call Page.DataBind()
You typically call DataBind() in your Page_Load
method.
Upvotes: 2
Reputation: 22823
Write a static method in code behind to test the role
public static bool IsAdmin(){
//chech and return true or false
}
In html call this method like
<li runat="server" id="liAdminUsers" visible ='<%# isAdmin() %>'>.....</li>
In this way you can control you logic like any other method.
Or you can directly set element visible false in your code behind
public static void IsAdmin(){
var admin = ....; //check current user role;
liAdminUsers.Visible = admin;
}
Upvotes: 0
Reputation: 15253
I once did something similar using a custom XML file with an attribute indicating if roles were applied or not for a particular application link - and if so, another attribute containing the role name. The code-behind would then check the custom membership store using the logged-in users network identity for authorization checking.
Upvotes: 0