0

我知道这个主题可能有点奇怪,但我不确定如何准确描述我的目标

我正在尝试在内容管理系统中执行一些基于角色的权限。我能想到的最好方法是从数据库中提取角色列表并将它们放在 CheckBoxList 中。从那里,我将检查值的逗号分隔字符串保存到数据库的页面详细信息中。最后,当页面被拉回时,我通过拉下逗号分隔的字符串并将其拆分为 String() 并循环遍历值来检查当前用户是否具有权限。

我担心的是,当我遍历 CheckBoxList 并将值转换为字符串时,循环方法会在字符串的末尾添加一个逗号......然后我必须在将逗号保存到数据库之前去掉它。

我的问题是,有没有更好的方法来做到这一点,这样我就不必在保存之前返回字符串并去除尾随逗号?

    ''# this is to get all selected items from
    ''# a checkboxlist and add it to a string
    ''# the reason for this is to insert the final string
    ''# into a database for future retrieval.
    Dim i As Integer
    Dim sb As StringBuilder = New StringBuilder()
    For i = 0 To CheckBoxList1.Items.Count - 1
        If CheckBoxList1.Items(i).Selected Then
            sb.Append(CheckBoxList1.Items(i).Value & ",")
        End If
    Next

    ''# now I want to save the string to the database
    ''# so I first have to strip the comma at the end
    Dim str As String = sb.ToString.Trim(",")
    ''# Then save str to the database

    ''# I have now retrieved the string from the 
    ''# database and I need to now add it to a One Dimensional String()
    Dim str_arr() As String = Split(str, ",")
    For Each s As String In str_arr
        ''# testing purposes only
        Response.Write(s & " -</br>")

        ''# If User.IsInRole(s) Then
        ''#     Do Stuff
        ''# End If
    Next
4

3 回答 3

1

将所有值放在字符串列表中,然后使用 String.Join 连接它们。我不会评论保持逗号分隔的列表而不是用户与角色的一对多关系。:-)

Dim values as List(Of String) = New List(Of String)()
For i = 0 To CheckBoxList1.Items.Count - 1 
    If CheckBoxList1.Items(i).Selected Then 
        values.Add( CheckBoxList1.Items(i).Value )
    End If 
Next

Dim str As String = String.Join( ",", values.ToArray() )
于 2010-02-10T17:25:07.123 回答
1

您是否可以简单地拥有一个包含对页面的引用(通过名称、路径或其他一些唯一 ID)和对角色的引用的数据库表?

我当然不是说这是最好的解决方案(无论如何),它只是一个例子:

角色表:

RoleId | RoleName
_________________
1      | Editor
2      | Administrator

页表:

PageId | PageName
8      | ~/Page1.aspx
9      | ~/OtherPlace/Page2.aspx

PageRole 表:

RoleId | PageId
2      | 8
2      | 9
1      | 9

然后,您将数据存储在联接表中,并在访问页面时根据当前页面拉回您的角色。当然,它根本不必基于页面,您可以轻松地将我的示例中的 Page 替换为 Permission。

于 2010-02-10T17:34:00.347 回答
-1

如果您使用 ASP.NET 成员资格,则可以为一个用户分配多个角色。

Roles.AddUserToRoles(username, roles);

Roles.IsUserInRole(role);

只是需要考虑的事情。

于 2010-02-10T17:28:58.817 回答