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
  • 195,001
  • 40
  • 254
  • 396
azamsharp
  • 19,710
  • 36
  • 144
  • 222

5 Answers5

8

As an alternative solution:

<% if (WebApplication1.SiteHelper.IsUserInRole("Admin"))
    {%>
        <asp:Button ID="btndisplayrole" 
                    Text="Admin Button" 
                    runat="server" 
                    OnClick="DisplayRoleClick" /> 
<%} %>
Jeroen
  • 60,696
  • 40
  • 206
  • 339
Adam Marshall
  • 81
  • 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
  • 98,240
  • 88
  • 296
  • 433
Tom Jelen
  • 2,559
  • 1
  • 24
  • 23
6

The following code worked:

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

Note that the aboe use the binding expression!

azamsharp
  • 19,710
  • 36
  • 144
  • 222
  • 2
    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,453
  • 5
  • 28
  • 33
-1
Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin").ToString() %>'

OR

Visible=<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>
James Skemp
  • 8,018
  • 9
  • 64
  • 107
shahkalpesh
  • 33,172
  • 3
  • 63
  • 88