0

我正在使用 ASP.Net 进行 Web 开发。我这里有情况。假设我的页面上有许多 HTML/ASP.Net 控件,并且我必须根据登录用户的角色设置每个控件的可见性。为此,我正在执行以下操作:

  1. 存储每个 Function-Name 和 Role 组合是 DB
  2. 在渲染期间,检查每个 HTML/ASP.Net 控件的角色权限。

例如:显示如下内容:

<asp:Label runat="server" id="Lbl1" visible='<%=CheckVisibility("Display","Admin")%>'>

public bool CheckVisibility(string FunctionName, string RoleName){
  // checks for db entry and returns bool value
}

问题是,我必须为所有控件执行此操作。有没有其他优化的方法可以做到这一点?请帮我

4

3 回答 3

1

Given only your description of what you're trying to solve, I would suggest you create your own controls which inherit from the built-in ones and add some properties to them. Then the controls can do the visibility check themselves. Something like

namespace StackOverflowTest
{
  public class Label : System.Web.UI.WebControls.Label
  {
    public string DisplayRoles { get; set; }

    protected override void OnPreRender(EventArgs e)
    {
      base.OnPreRender(e);

      Visible = PermissionHelper.CheckPermission("Display", DisplayRoles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
    }
  }

  public static class PermissionHelper
  {
    public static bool CheckPermission(string function, string[] allowedRoles)
    {
      // TODO: hit some sort of cache, so you don't make a bajillion queries to the DB
      return true;
    } 
  }
}

And then if you put this in your web.config (sorry, can't figure out how to do proper XML formatting here): <system.web> <pages> <controls> <add tagPrefix="sot" assembly="StackOverflowTest" namespace="StackOverflowTest"/> </controls> </pages> </system.web>

You can add this to your markup: <sot:Label ID="AdminLabel" runat="server" Text="Bind this in OnLoad/!IsPostback or something" DisplayRoles="Admin,Management" />

This is just one of the many ways you can do this. It all depends on the requirements, of course. But I'm pretty sure you'll need your own classes for controls to have the possibility of making it manageable.

于 2012-12-27T06:25:14.660 回答
0

C# code:

public enum previlageType
{
    superAdminPrevilages=1,
    partnerPrevilages = 2,
    dealerPrevilages = 3,
    customerPrevilages=4

}

if ((previlageType)Enum.Parse(typeof(previlageType), Session["previlageType"].ToString())== previlageType.partnerPrevilages)
{
    accordion.Visible = false;
}

ASP code:

<div id="accordion" runat="server">
Hello World, I'l be Hidden if a person with partner previlages is logged in. BUt will be visible if superadmin or any person except Partner logs in.
</div>

Hope it helps

于 2012-12-27T06:27:46.217 回答
0

如果您使用的是母版页,则可以在加载时获取所有子页面控件(获取 contentplaceholders,然后获取 contentplaceholder 控件)。

然后,当您拥有所有控件名称时,在您的表上进行查找并在需要时将其可见性设置为 false。

(下面是vb,但翻译应该很容易。)

        For Each cp As String In Me.ContentPlaceHolders
            For Each ctl As Control In Me.FindControl(cp).Controls
                If adminonly.Contains(ctl.ID) Then
                    ctl.Visible = False
                End If
            Next
        Next
于 2015-07-24T14:57:12.480 回答