How to enable and disable a button based on a user role?

I have a role called "member" and another "admin" on Asp.Net.

I did this before, this button should be visible or not, and I'm sure of it, but I can’t get the correct code (aspx.cs) to disable the button so that it can be displayed, but not on all available.

<asp:Button ID="Button4" runat="server" PostBackUrl="~/report.aspx" Text="print in report format" Width="173px" Enabled='<%# HttpContext.Current.User.IsInRole("Admin") %>' /> 

I want whenever the "report" button is pressed to enter the membership,

+3
source share
6 answers

You must set the value of the Button.Enabled property according to the return value of the HttpContext.Current.User.IsInRole("admin") function.

Or in html:

 <Button ... Enabled='<%# HttpContext.Current.User.IsInRole("Admin") %>' ... > 

Or in the code behind:

 Button.Enabled = HttpContext.Current.User.IsInRole("Admin"); 
+4
source
 if (HttpContext.Current.User.IsInRole("member")) { //enable/disable here } 
+4
source

In Page_Load, after checking the role, you can set IsEnabled for the False button.

eg. buttonLogin.Enabled = (IsUserInRole (Admin));

+3
source

Either I'm missing something, or just:

 button.Enabled = false; 
+2
source

I assume that you are using an ASP.NET control - if you then need to set the Visible and Enabled button properties to false

+1
source

The main problem you are facing is a hash tag: <%# used to identify the binding. If you do not call this in gridview or formview or something else, this will not work. I would recommend installing it in the code behind, as suggested by @Muhammad Akhtar, but if you're damn bent for the skin using the html side, it probably should be:

 Enabled='<%= HttpContext.Current.User.IsInRole("Admin").ToString() %>' 
+1
source

All Articles