Assigning a visible button property to a static method result

I am trying to hide a button based on a user 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" visible "

+9
css embedded-code
Dec 15 '08 at 21:14
source share
5 answers

Kind of an interesting problem. But, as the error message says, the string <%= WebApplication1.SiteHelper.IsUserInRole("Admin") %> cannot be converted to logical.

Unfortunately, I cannot explain why the expression is not evaluated, but is instead treated as a string.

The reason your expression <%# %> works as expected is because it is interpreted 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 it hooks this method before the Control.Databinding event on your control. As you can see, <%# %> this time is correctly processed as server code, and not just a random string.

So, I think the solution is to use data binding or go to code code, as Andreas Knudsen suggests.

+7
Dec 15 '08 at 23:43
source share

As an alternative solution:

 <% if (WebApplication1.SiteHelper.IsUserInRole("Admin")) {%> <asp:Button ID="btndisplayrole" Text="Admin Button" runat="server" OnClick="DisplayRoleClick" /> <%} %> 
+6
May 25 '12 at 2:36 a.m.
source share

The following code worked:

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

Note that aboe uses a binding expression!

+5
Dec 15 '08 at 21:22
source share

how easy is it to do this in code, for example, on the page_Load?

 public void Page_Load( object sender, EventArgs e ) { btndisplayrole.Visible = WebApplication1.SiteHelper.IsUserInRole("Admin"); } 
+2
Dec 15 '08 at 22:47
source share
 Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin").ToString() %>' 

OR

 Visible=<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %> 
-one
Dec 15 '08 at 21:17
source share



All Articles