10

I am trying to hide the button based on the user's role using the following code:

 <asp:Button ID="btndisplayrole" Text="Admin Button" Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' runat="server" OnClick="DisplayRoleClick" />

But when I run the above code I get the following error message:

Cannot create an object of type 'System.Boolean' from its string representation '<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' for the 'Visible'

Lundin
  • 174,148
  • 38
  • 234
  • 367
azamsharp
  • 19,049
  • 36
  • 140
  • 219

5 Answers5

7

As an alternative solution:

<% if (WebApplication1.SiteHelper.IsUserInRole("Admin"))
    {%>
        <asp:Button ID="btndisplayrole" 
                    Text="Admin Button" 
                    runat="server" 
                    OnClick="DisplayRoleClick" /> 
<%} %>
Jeroen
  • 56,917
  • 35
  • 193
  • 305
Adam Marshall
  • 71
  • 1
  • 1
7

Kind of an interesting issue.. But as the error message states, the string <%= WebApplication1.SiteHelper.IsUserInRole("Admin") %> cannot be converted to a boolean.

Unfortunately i cannot explain why the expression isn't evaluated, but instead is treated like a string.

The reason why your <%# %> expression works as expected, is because it is treated much differently. When the Page is compiled into a class, then the compiler creates an event handler similar to this:

public void __DataBindingButton2(object sender, EventArgs e)
{
    Button button = (Button) sender;
    Page bindingContainer = (Page) button.BindingContainer;
    button.Visible = HttpContext.Current.User.IsInRole("admin");
}

and hooks this method up to the Control.Databinding event on your control. As you can see, the <%# %> is this time properly treated as server code, and not just a random string.

So i guess the solution is either to use databinding, or go to the codebehind as AndreasKnudsen suggests.

abatishchev
  • 95,331
  • 80
  • 293
  • 426
Tom Jelen
  • 2,559
  • 1
  • 23
  • 23
6

The following code worked:

Visible='<%# WebApplication1.SiteHelper.IsUserInRole("Admin") %>'

Note that the aboe use the binding expression!

azamsharp
  • 19,049
  • 36
  • 140
  • 219
  • 1
    Actually the above code is NOT what I needed since now I have to bind the page in order to execute the code! – azamsharp Dec 15 '08 at 21:24
2

how about just doing it in the codebehind, for instance on Page_Load ?

public void Page_Load( object sender, EventArgs e )
{
   btndisplayrole.Visible = WebApplication1.SiteHelper.IsUserInRole("Admin");
}
AndreasKnudsen
  • 3,373
  • 4
  • 27
  • 30
-1
Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin").ToString() %>'

OR

Visible=<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>
James Skemp
  • 7,696
  • 9
  • 60
  • 101
shahkalpesh
  • 32,561
  • 3
  • 63
  • 86