how to enable and disable button based on user role?

半世苍凉 提交于 2019-12-01 07:15:19

You have to set the Button.Enabled property value to according to the HttpContext.Current.User.IsInRole("admin") function returned value.

Either in html:

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

Or in code behind:

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

In the Page_Load after checking for the role you may be able to set the IsEnabled for the Button to be False.

e.g. buttonLogin.Enabled = (IsUserInRole(Admin));

Either I'm missing something or the solution is simply:

button.Enabled = false;

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

The primary problem you have here is the hash mark: <%# is used to identify a binding. Unless you're calling this in a gridview or a formview or something, this will not work. I would recommend setting it in the code behind as suggested by @Muhammad Akhtar, but if you're hell bent for leather on using the html side it should probably be:

Enabled='<%= HttpContext.Current.User.IsInRole("Admin").ToString() %>'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!