Wednesday, March 25, 2015

Get Assigned Roles With LINQ

Here's one way of creating a RadGrid with assigned roles for users. 

   <telerik:RadGrid runat="server" ID="gridUsers" AllowSorting="True"
                   AutoGenerateColumns="False" GroupPanelPosition="Top" 
                   ResolvedRenderMode="Classic"
                   onneeddatasource="gridUsers_NeedDataSource"                     onitemdatabound="gridUsers_ItemDataBound">         <MasterTableView>             <Columns>                 <telerik:GridBoundColumn DataField="userName"                      HeaderText="User Name"                      UniqueName="colUserName">                 </telerik:GridBoundColumn>                 <telerik:GridBoundColumn DataField="roles"                      HeaderText="Roles"                      UniqueName="colRoles">                 </telerik:GridBoundColumn>                 <telerik:GridBoundColumn DataField="isApproved"                      HeaderText="Active User?"                      UniqueName="colIsApproved">                 </telerik:GridBoundColumn>             </Columns>         </MasterTableView>     </telerik:RadGrid>

using System;
using System.Linq;
using System.Web.Security;
using Telerik.Web.UI;

    protected void gridUsers_NeedDataSource(object sender, 
                     Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        try 
        { 
            using (var dc = new  MyModel.EntitiesModel())
            {
                var u = dc.Aspnet_Users.Select(a => new
                {
                    userName = a.UserName,
                    roles = string.Join(","Roles.GetRolesForUser(a.UserName)),
                    isApproved = (Membership.GetUser(a.UserName)).IsApproved
                });
                if (null != u)
                {
                    this.gridUsers.DataSource = u.ToList();
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    protected void gridUsers_ItemDataBound(object sender, 
                              Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem dataItem = (GridDataItem)e.Item;
            if (dataItem["colIsApproved"].Text != null &&
dataItem["colIsApproved"].Text == "False")
            {
                dataItem["colIsApproved"].BackColor = System.Drawing.Color.Red;
                dataItem["colIsApproved"].ToolTip = "This person cannot login.";
            }
        }
    }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.