简体   繁体   English

ASP.NET-可以创建一个DetailsView,仅具有特定角色的用户将某些字段视为可编辑的吗?

[英]ASP.NET - Can you make a DetailsView where only users with specific roles see some fields as editable?

For example lets say I want only admins to be able to see and edit CustomerID in details view, moderators can see this value but it is not editable, and regular users cannot even see it. 例如,假设我只希望管理员能够在详细信息视图中查看和编辑CustomerID,主持人可以看到此值,但该值不可编辑,而普通用户甚至看不到它。 Is this possible? 这可能吗?

Here you go. 干得好。 I tried many google searches and no one could clearly explain it. 我尝试了许多Google搜索,但没人能清楚地解释它。 You have to perform this on the PreRender Event. 您必须在PreRender事件上执行此操作。 Please not that this code snippet uses the Membership Provider in .net to check if a user is in a role. 请不要在此代码段中使用.net中的成员资格提供程序来检查用户是否在角色中。 If you have your own custom tables you will have to write a custom function that checks if a user is in one of your custom roles. 如果您有自己的自定义表,则必须编写一个自定义函数来检查用户是否在您的自定义角色中。 Also please not that this solution is using ItemTemplates not BoundFields. 也请不要因为此解决方案使用的是ItemTemplates而不是BoundFields。

protected void detailsView_OnPreRender(object sender, EventArgs e)
    {
        if (dvPackage.CurrentMode == DetailsViewMode.Edit)
        {
           //disables/enables a the dropdown for Process Status if the user has the RLIST role
           TextBox txtCustomID = (TextBox)Utilities.FindControlRecursive(dvPackage, "txtCustomID ");
           txtCustomID.Visible = false;
           if (User.IsInRole("Admin"))
           {
              txtCustomID.Visible = true;

         }
     }

Here's the find control recursive funciton. 这是查找控件的递归函数。 Free of charge. 免费的。

public static Control FindControlRecursive(Control ctlRoot, string sControlId)
    {
        // if this control is the one we are looking for, break from the recursion    
        // and return the control.    
        if (ctlRoot.ID == sControlId)
        {
            return ctlRoot;
        }
        // loop the child controls of this parent control and call recursively.    
        foreach (Control ctl in ctlRoot.Controls)
        {
            Control ctlFound = FindControlRecursive(ctl, sControlId);
            // if we found the control, return it.        
            if (ctlFound != null)
            {
                return ctlFound;
            }
        }// we never found the control so just return null.    
        return null;
    }

我建议Web用户控件或多视图根据用户角色来处理切换视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM