Assigning Visible Property of the Button to a Static Method Result

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’

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

As an alternative solution:

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

Method 3

The following code worked:

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

Note that the aboe use the binding expression!

Method 4

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");
}

Method 5

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

OR

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x