checkboxlist到字符串,保存到数据库,然后转换为数组
-
19-09-2019 - |
题
我知道这个主题可能有些奇怪,但我不确定如何准确描述我的目标
我正在尝试在内容管理系统中执行一些基于角色的权限。我能想到的最好的方法是从数据库中提取角色列表,并将其放入CheckboxList。从那里,我将检查值的逗号分开的字符串保存到数据库的页面详细信息中。最后,当页面被撤回时,我通过将逗号分隔的字符串并将其分配到字符串()并循环浏览值来检查当前用户是否有权限。
我担心的是,当我循环浏览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
解决方案
将所有值放在字符串列表中,然后使用字符串。加入将它们串联。我不会评论保留逗号分隔的列表,而不是用户与角色的一对多关系。 :-)
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() )
其他提示
您是否可以简单地拥有一个数据库表,其中包含对页面的引用(无论是名称,路径还是其他独特的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
然后,您将数据存储在加入表中,并且在访问页面时,根据当前页面撤回角色。当然,它根本不必基于页面,您可以轻松地在我的示例中替换页面。
If you use ASP.NET membership, you can assign multiple roles to a user.
Roles.AddUserToRoles(username, roles);
Roles.IsUserInRole(role);
Just something to consider.
不隶属于 StackOverflow