Creating Custom Role Manager With Dynamic Menus in ASP.Net

Introduction

This article shows how to create a menu and sub menus depending on user roles and also how to provide read and write access to users.

The main point in this article is that depending on user login I will display a menu to users and admin.

Microsoft also provides its own tool, the Web Site Administration Tool (WAT) for managing user roles and authorization.

Which works in what way?

Tables used

dbo.MTDUsers
dbo.MTDMenu
dbo.MTDroles
dbo.MTDMenuSave
dbo.MTDSubMenu
dbo.MTDSubMenuSave

And I am also providing the entire solution with SQL script.

I will go through all the main points because this application is big.

For this I have created a Custom role manager with access rights.

Step 1

We can do Custom Authentication and Authorization in ASP.NET when the user registers with us.

Let's start with login and registration.



In this I have created a simple form for login and registration.



This registration details will be stored in Table dbo.MTDUsers.

After login we will display a menu and forms that users can access.

1. For creating and roles I have created a page [ AddRoles.aspx ]

Snapshot AddRoles.aspx



In this form, we will add roles, such as Admin, Users, SuperAdmin and so on.

On button Button1

  1. <asp:Button ID="Button1" runat="server" Text="Save Roles" OnClick="Button1_Click" /> 

I have written code for saving roles in table (MTDroles).

I am also showing an error message if (TxtUserRoles.Text) is blank using script manager.

  1. protected void Button1_Click(object sender, EventArgs e)    
  2. {     
  3.     if (TxtUserRoles.Text == "")     
  4.     {     
  5.          ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert",              
  6.          "alert('Please Enter User Role');"true);     
  7.     }     
  8.     else     
  9.     {     
  10.         SqlCommand cmd = new SqlCommand("MTDUserRolesInsert", con);     
  11.         cmd.CommandType = CommandType.StoredProcedure;     
  12.         cmd.Parameters.AddWithValue("@RolesName", TxtUserRoles.Text);     
  13.         con.Open();     
  14.         cmd.ExecuteNonQuery();     
  15.         con.Close();     
  16.         TxtUserRoles.Text = "";     
  17.         getdata();     
  18.     }     
  19. } 

And also binding a GridView as the user enters roles.

In this function, I am just getting all the data from the table (MTDroles) and displaying.

  1. public void getdata()     
  2. {     
  3.   SqlCommand cmd = new SqlCommand("Usp_MTDgetroles", con);     
  4.   cmd.CommandType = CommandType.StoredProcedure;     
  5.   SqlDataAdapter da = new SqlDataAdapter();     
  6.   da.SelectCommand = cmd;     
  7.   DataSet ds = new DataSet();     
  8.   da.Fill(ds);     
  9.   if (ds.Tables.Contains("Table") == true)     
  10.   {     
  11.         if (ds.Tables[0].Rows.Count > 0)     
  12.         {     
  13.             GVRoles.DataSource = ds.Tables[0];     
  14.             GVRoles.DataBind();     
  15.         }     
  16.     }     
  17. } 

I can also delete roles if I don't want them. But if it is used then it can't be deleted.

  1. protected void GVRoles_RowCommand(object sender, GridViewCommandEventArgs e)  
  2. {  
  3.     if (e.CommandName == "Deleterole")     
  4.     {     
  5.         string id = e.CommandArgument.ToString();     
  6.         SqlCommand cmd = new SqlCommand("usp_DeleteRoles", con);     
  7.         cmd.CommandType = CommandType.StoredProcedure;     
  8.         cmd.Parameters.AddWithValue("@RolesID", id);     
  9.         con.Open();     
  10.         string s = cmd.ExecuteScalar().ToString();     
  11.         con.Close();     
  12.         ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('" + s + "');"true);     
  13.     }  
  14. } 

Step 2
 
I have now added the roles successfully. I will now assign roles to registered users.

Snapshot before adding users.



For assigning roles I am loading all the roles in the role dropdown list.

And in another drop-down list I am loading all the registered user names.

After selecting I am just going to assign roles.

On Pageload I am binding a dropdown list.
  1. protected void Page_Load(object sender, EventArgs e)   
  2. {  
  3.     if (!IsPostBack)     
  4.     {     
  5.         Loadroles();     
  6.         DrpGetuser();  
  7.     }  
  8. } 

Binding DrpRoles

  1. public void Loadroles()    
  2. {     
  3.     SqlCommand cmd = new SqlCommand("Usp_MTDgetroles", con);     
  4.     cmd.CommandType = CommandType.StoredProcedure;     
  5.     SqlDataAdapter da = new SqlDataAdapter();     
  6.     da.SelectCommand = cmd;     
  7.     DataSet ds = new DataSet();     
  8.     da.Fill(ds);     
  9.     if (ds.Tables.Contains("Table") == true)     
  10.     {     
  11.         if (ds.Tables[0].Rows.Count > 0)     
  12.         {     
  13.              DrpRoles.DataSource = ds.Tables[0];     
  14.              DrpRoles.DataTextField = ds.Tables[0].Columns[1].ColumnName;     
  15.              DrpRoles.DataValueField = ds.Tables[0].Columns[0].ColumnName;     
  16.              DrpRoles.DataBind();     
  17.         }     
  18.     }     
  19. } 

Binding DrpUser

Getting all roles from the table MTDUsers and displaying them:

  1. protected void DrpGetuser()     
  2. {     
  3.     SqlCommand cmd = new SqlCommand("select * from MTDUsers", con);     
  4.     cmd.CommandType = CommandType.Text;     
  5.     SqlDataAdapter da = new SqlDataAdapter();     
  6.     da.SelectCommand = cmd;     
  7.     DataSet ds = new DataSet();     
  8.     da.Fill(ds);     
  9.     if (ds.Tables.Contains("Table") == true)     
  10.     {     
  11.          if (ds.Tables[0].Rows.Count > 0)     
  12.          {     
  13.                 DrpUser.DataSource = ds.Tables[0];     
  14.                 DrpUser.DataTextField = ds.Tables[0].Columns[1].ColumnName;     
  15.                 DrpUser.DataValueField = ds.Tables[0].Columns[0].ColumnName;     
  16.                 DrpUser.DataBind();     
  17.          }     
  18.      }     
  19. } 

On Button Assign

Here I will update roles in the table MTDUsers.

For the update I am passing the following 2 parameters:

  1. Roles
  2. Userid

  1. protected void btnassign_Click(object sender, EventArgs e)   
  2. {   
  3.     if (DrpUser.SelectedIndex == 0)    
  4.     {     
  5.         ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('Please select Username');"true);     
  6.     }     
  7.     else if (DrpRoles.SelectedIndex == 0)     
  8.     {     
  9.         ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('Please select Roles');"true);   
  10.     }     
  11.     else     
  12.     {     
  13.         SqlCommand cmd = new SqlCommand("usp_updateuserRole", con);     
  14.         cmd.CommandType = CommandType.StoredProcedure;     
  15.         cmd.Parameters.AddWithValue("@UserID", DrpUser.SelectedValue);     
  16.         cmd.Parameters.AddWithValue("@RoleID", DrpRoles.SelectedValue);     
  17.         con.Open();     
  18.         string result = cmd.ExecuteScalar().ToString();     
  19.         con.Close();     
  20.         ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('" + result + "');"true);     
  21.     }  
  22. } 

On drpUser SelectedIndexChanged I am binding a grid to show what roles are assigned to the users.

  1. protected void DrpUser_SelectedIndexChanged(object sender, EventArgs e)    
  2. {     
  3.     if (DrpUser.SelectedIndex != 0)     
  4.     {     
  5.        getdata(DrpUser.SelectedValue);     
  6.    }     
  7. }          
  8. public void getdata(string UserID)     
  9. {     
  10.     SqlCommand cmd = new SqlCommand("usp_getallusers", con);     
  11.     cmd.CommandType = CommandType.StoredProcedure;     
  12.     cmd.Parameters.AddWithValue("@UserID", UserID);     
  13.     SqlDataAdapter da = new SqlDataAdapter();     
  14.     da.SelectCommand = cmd;     
  15.     DataSet ds = new DataSet();     
  16.     da.Fill(ds);     
  17.     if (ds.Tables.Contains("Table") == true)     
  18.     {     
  19.         if (ds.Tables[0].Rows.Count > 0)     
  20.         {     
  21.             GVRoles.DataSource = ds.Tables[0];     
  22.             GVRoles.DataBind();     
  23.         }     
  24.     }     
  25. } 

Snapshot after assign.



Step 3

After assigning a role I will add a menu. [AddMenu.aspx]

For assigning the menu I just need to select roles.

Provide menu name.

Provide menu URL.

For example, how to enter the path of the URL: ../foldername/your page name

Path to enter: ../Contactus/SubContact.aspx

Create a separate folder for pages we will add.
 


I know you have questions in your mind, such as what to do if I have subpages.

Just keep them in the same folder such as Aboutus.aspx; that is the main page and if you use subaboutus.aspx then keep it in the same folder.

Snapshot of adding Menu
 


On page load I am binding a drop downlist and GridView.
  1. protected void Page_Load(object sender, EventArgs e)   
  2. {  
  3.    if (!IsPostBack)     
  4.    {     
  5.         getdata();     
  6.         GetRoles();     
  7.     }  
  8. } 

1. The getdata() method shows records as I enter data.

  1. public void getdata()     
  2. {     
  3.     SqlCommand cmd = new SqlCommand("Usp_MTDgetMenu", con);     
  4.     cmd.CommandType = CommandType.StoredProcedure;     
  5.     SqlDataAdapter da = new SqlDataAdapter();     
  6.     da.SelectCommand = cmd;     
  7.     DataSet ds = new DataSet();     
  8.     da.Fill(ds);     
  9.     if (ds.Tables.Contains("Table") == true)    
  10.     {     
  11.          if (ds.Tables[0].Rows.Count > 0)     
  12.          {     
  13.                 GVmenu.DataSource = ds.Tables[0];     
  14.                 GVmenu.DataBind();     
  15.          }     
  16.     }     
  17. } 

2. The GetRoles() method is for getting roles.

  1. public void GetRoles()     
  2. {     
  3.      SqlCommand cmd = new SqlCommand("Usp_MTDgetMenu", con);     
  4.      cmd.CommandType = CommandType.StoredProcedure;     
  5.      SqlDataAdapter da = new SqlDataAdapter();     
  6.      da.SelectCommand = cmd;     
  7.      DataSet ds = new DataSet();     
  8.      da.Fill(ds);     
  9.      if (ds.Tables.Contains("Table1") == true)     
  10.      {     
  11.           if (ds.Tables[1].Rows.Count > 0)     
  12.           {     
  13.                 DrpRoles.DataSource = ds.Tables[1];     
  14.                 DrpRoles.DataTextField = ds.Tables[1].Columns[1].ColumnName;     
  15.                 DrpRoles.DataValueField = ds.Tables[1].Columns[0].ColumnName;     
  16.                 DrpRoles.DataBind();     
  17.          }     
  18.      }     
  19. } 

On save button

Here depending on roles we are adding menu.

  1. protected void Save_Click(object sender, EventArgs e)     
  2. {      
  3.     if (DrpRoles.SelectedIndex == 0)     
  4.     {     
  5.         ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('Please Select Roles');"true);     
  6.     }     
  7.     else if (TxtMenuname.Text == "")     
  8.     {     
  9.         ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('Please Enter Menu name');"true);     
  10.     }     
  11.     else if (txtmenuURL.Text == "")     
  12.     {     
  13.         ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('Please Enter Menu URL');"true);     
  14.     }     
  15.     else     
  16.     {     
  17.         SqlCommand cmd = new SqlCommand("Usp_MTDMTDMenuInsert", con);     
  18.         cmd.CommandType = CommandType.StoredProcedure;     
  19.         cmd.Parameters.AddWithValue("@MenuName", TxtMenuname.Text);     
  20.         cmd.Parameters.AddWithValue("@MenuURL", txtmenuURL.Text);     
  21.         cmd.Parameters.AddWithValue("@RoleID", DrpRoles.SelectedValue);     
  22.         con.Open();     
  23.         cmd.ExecuteNonQuery();     
  24.         con.Close();     
  25.         getdata();     
  26.     }     
  27. } 

Here I am saving data and also calling the getdata() method after saving for displaying the current data as I add it.

And GridView also has a delete feature for deleting.

GridView Snapshot.

  1. protected void GVmenu_RowCommand(object sender, GridViewCommandEventArgs e)     
  2. {     
  3.      if (e.CommandName == "Deleterole")     
  4.      {     
  5.         string id = e.CommandArgument.ToString();     
  6.         SqlCommand cmd = new SqlCommand("usp_DeleteMTDMenu", con);     
  7.         cmd.CommandType = CommandType.StoredProcedure;     
  8.         cmd.Parameters.AddWithValue("@MenuID", id);     
  9.         con.Open();     
  10.         string s = cmd.ExecuteScalar().ToString();     
  11.         ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert",      
  12.         "alert('" + s + "');"true);                          
  13.           con.Close();     
  14.       }     
  15. }

Now we have completed the adding of the menu and will proceed to adding a submenu.

Step 4

Adding submenu for the Menu. [AddSubMenu.aspx]



Now we have completed the adding of the mainmenu and now we will add a submenu.

In other words if we have the main menu Chocolate.

All the submenus will be:
  1. Strawberries chocolate.
  2. Hazelnut chocolate
  3. Caramel chocolate
  4. Milk chocolate.

For adding a submenu we need to:

  1. Select Roles
  2. Enter Menu Name
  3. Enter sub Menu Name
  4. Enter sub Menu URL.
  5. Last Save and its done.

On page load of [AddSubMenu.aspx]

  1. protected void Page_Load(object sender, EventArgs e)     
  2. {     
  3.      if (!IsPostBack)     
  4.      {     
  5.             getdata();     
  6.             GetRoles();     
  7.       }    
  8. } 

1. The getdata() method is for showing records as I enter data.

  1. public void getdata()     
  2. {     
  3.      SqlCommand cmd = new SqlCommand("Usp_MTDgetSubMenu", con);     
  4.      cmd.CommandType = CommandType.StoredProcedure;     
  5.      SqlDataAdapter da = new SqlDataAdapter();     
  6.      da.SelectCommand = cmd;     
  7.      DataSet ds = new DataSet();     
  8.      da.Fill(ds);     
  9.      if (ds.Tables.Contains("Table") == true)     
  10.      {     
  11.           if (ds.Tables[0].Rows.Count > 0)     
  12.           {     
  13.                 GVmenu.DataSource = ds.Tables[0];     
  14.                 GVmenu.DataBind();     
  15.           }     
  16.     }     
  17. } 

2. The GetRoles() method is for getting roles.

  1. public void GetRoles()     
  2. {     
  3.     SqlCommand cmd = new SqlCommand("Usp_MTDgetroles", con);     
  4.     cmd.CommandType = CommandType.StoredProcedure;     
  5.     SqlDataAdapter da = new SqlDataAdapter();     
  6.     da.SelectCommand = cmd;     
  7.     DataSet ds = new DataSet();     
  8.     da.Fill(ds);     
  9.     if (ds.Tables.Contains("Table") == true)     
  10.     {     
  11.         if (ds.Tables[0].Rows.Count > 0)     
  12.         {     
  13.               DrpRoles.DataSource = ds.Tables[0];     
  14.               DrpRoles.DataTextField = ds.Tables[0].Columns[1].ColumnName;     
  15.               DrpRoles.DataValueField = ds.Tables[0].Columns[0].ColumnName;     
  16.               DrpRoles.DataBind();     
  17.         }     
  18.     }     
  19. } 

After a page load on the change of the DrpRoles dropdownlist I am binding the Drpmenu dropdownlist.

Because depending on the Drproles dropdownlist I am binding the Drpmenu dropdownlist.

  1. <asp:DropDownList ID="DrpRoles" Width="150px" runat="server" AppendDataBoundItems="True"     
  2. AutoPostBack="True" OnSelectedIndexChanged="DrpRoles_SelectedIndexChanged">     
  3. <asp:ListItem Value="0">Select</asp:ListItem>     
  4. </asp:DropDownList>    

  1. protected void DrpRoles_SelectedIndexChanged(object sender, EventArgs e)     
  2. {    
  3.    SqlCommand cmd = new SqlCommand("Usp_MTDGetMenuByRoles", con);     
  4.    cmd.Parameters.AddWithValue("@roleID", DrpRoles.SelectedValue);     
  5.    cmd.CommandType = CommandType.StoredProcedure;     
  6.    SqlDataAdapter da = new SqlDataAdapter();     
  7.    da.SelectCommand = cmd;     
  8.    DataSet ds = new DataSet();     
  9.    da.Fill(ds);     
  10.    if (ds.Tables.Contains("Table") == true)     
  11.    {     
  12.        if (ds.Tables[0].Rows.Count > 0)     
  13.        {     
  14.            DrpMenu.DataSource = ds.Tables[0];     
  15.            DrpMenu.DataTextField = ds.Tables[0].Columns[1].ColumnName;     
  16.            DrpMenu.DataValueField = ds.Tables[0].Columns[0].ColumnName;     
  17.            DrpMenu.DataBind();     
  18.        }     
  19.    }  
  20. } 

 

Here you can see I have used the DrpRoles.SelectedValue for filling the Drpmenu dropdownlist.

After selecting and entering all the data I will click on the Save button to save the submenu.
  1. protected void Save_Click(object sender, EventArgs e)     
  2. {     
  3.      SqlCommand cmd = new SqlCommand("Usp_MTDMTDMTDSubMenuInsert", con);     
  4.      cmd.CommandType = CommandType.StoredProcedure;     
  5.      cmd.Parameters.AddWithValue("@SubmenuName", txtsubmenu.Text);     
  6.      cmd.Parameters.AddWithValue("@SubMenuURL", txtmenuURL.Text);     
  7.      cmd.Parameters.AddWithValue("@MenuID", DrpMenu.SelectedValue);     
  8.      cmd.Parameters.AddWithValue("@RoleID", DrpRoles.SelectedValue);     
  9.      con.Open();     
  10.      cmd.ExecuteNonQuery();     
  11.      con.Close();     
  12.      getdata();     
  13. } 

On save I am saving SubmenuName,SubmenuURL,MenuID,RoleID.

And you can see after saving data and also I am calling the getdata() method after.

Saving for displaying current data as I add it.

And GridView also has a delete feature for deleting.

Snapshot of adding a submenu.



Step 5
 
This is the Main process of Role Manager to save roles according to the user.

Here is a snapshot.
 


Here I took the following 2 DropDownLists:
  1. Role
  2. UserName.

After selecting Roles you will see a GridView that contains a Menu and Submenu.



This GridView contains all the data you entered into the menu and submenu.

Now you can provide the following rights to the page.
  1. Read.
  2. Write
  3. Full Write

And click on the Save Role Assign Button to save its final step to do this.

The Design of [ AssignRoleToUser.aspx ]

  1. Contains 2 Dropdownlist
  2. GridView Inside Grideview 1 for Mainmenu and Other for Sub menu.

The Page Load Method of [ AssignRoleToUser.aspx ]

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!IsPostBack)  
  4.     {  
  5.         LoadMenu();  
  6.         DrpGetuser();  
  7.   
  8.     }  
  9. } 

1. The GetRoles() method is for getting roles.

  1. public void LoadMenu()  
  2. {  
  3.     SqlCommand cmd = new SqlCommand("Usp_MTDgetroles", con);  
  4.     cmd.CommandType = CommandType.StoredProcedure;  
  5.     SqlDataAdapter da = new SqlDataAdapter();  
  6.     da.SelectCommand = cmd;  
  7.     DataSet ds = new DataSet();  
  8.     da.Fill(ds);  
  9.     if (ds.Tables.Contains("Table") == true)  
  10.     {  
  11.         if (ds.Tables[0].Rows.Count > 0)  
  12.         {  
  13.             DrpRoles.DataSource = ds.Tables[0];  
  14.             DrpRoles.DataTextField = ds.Tables[0].Columns[1].ColumnName;  
  15.             DrpRoles.DataValueField = ds.Tables[0].Columns[0].ColumnName;  
  16.             DrpRoles.DataBind();  
  17.         }  
  18.     }  
  19. } 

2. The DrpGetuser() method is for getting all the registered UserNames. sg

Save Button

  1. <asp:Button ID="Save" runat="server" Text="Save Role Assign"    
  2. nclick="Save_Click" /> 

Here is the code snippets for the Save Button.

  1. protected void Save_Click(object sender, EventArgs e)  
  2. {  
  3.     for (int i = 0; i < GridView1.Rows.Count; i++)  
  4.     {  
  5.         CheckBox CHKR = (CheckBox)GridView1.Rows[i].FindControl("CHKR");  
  6.         CheckBox CHKW = (CheckBox)GridView1.Rows[i].FindControl("CHKW");  
  7.         CheckBox CHKB = (CheckBox)GridView1.Rows[i].FindControl("CHKB");  
  8.         Label lblMenuName = (Label)GridView1.Rows[i].FindControl("lblMenuName");  
  9.         HiddenField HDMID = (HiddenField)GridView1.Rows[i].FindControl("HDmenuID");  
  10.         SqlCommand cmd = new SqlCommand("Usp_InsertMTDMenu", con);  
  11.         cmd.CommandType = CommandType.StoredProcedure;  
  12.         cmd.Parameters.AddWithValue("@MenuID", HDMID.Value);  
  13.         cmd.Parameters.AddWithValue("@MenuName", lblMenuName.Text);  
  14.         if (CHKR.Checked)  
  15.         {  
  16.             cmd.Parameters.AddWithValue("@MRead", 1);  
  17.         }  
  18.         else  
  19.         {  
  20.             cmd.Parameters.AddWithValue("@MRead", 0);  
  21.         }  
  22.         if (CHKW.Checked)  
  23.         {  
  24.             cmd.Parameters.AddWithValue("@MWrite", 1);  
  25.         }  
  26.         else  
  27.         {  
  28.             cmd.Parameters.AddWithValue("@MWrite", 0);  
  29.         }  
  30.         if (CHKB.Checked)  
  31.         {  
  32.             cmd.Parameters.AddWithValue("@MBoth", 1);  
  33.         }  
  34.         else  
  35.         {  
  36.             cmd.Parameters.AddWithValue("@MBoth", 0);  
  37.         }  
  38.         cmd.Parameters.AddWithValue("@UID", DrpUser.SelectedValue);  
  39.         cmd.Parameters.AddWithValue("@RID", DrpRoles.SelectedValue);  
  40.         con.Open();  
  41.         cmd.ExecuteNonQuery();  
  42.         con.Close();  
  43.         GridView GV2 = (GridView)GridView1.Rows[i].FindControl("GridView2");  
  44.         for (int j = 0; j < GV2.Rows.Count; j++)  
  45.         {  
  46.             CheckBox CHKRSUB = (CheckBox)GV2.Rows[j].FindControl("CHKRSUB");  
  47.             CheckBox CHKWSUB = (CheckBox)GV2.Rows[j].FindControl("CHKWSUB");  
  48.             CheckBox CHKBSUB = (CheckBox)GV2.Rows[j].FindControl("CHKBSUB");  
  49.             Label lblsubmenu = (Label)GV2.Rows[j].FindControl("lblsubmenu");  
  50.             HiddenField HDsubmenuID = (HiddenField)GV2.Rows[j].FindControl("HDsubmenuID");  
  51.             SqlCommand cmd1 = new SqlCommand("Usp_InsertMTDSubMenu", con);  
  52.             cmd1.CommandType = CommandType.StoredProcedure;  
  53.             cmd1.Parameters.AddWithValue("@SubMenuID", HDsubmenuID.Value);  
  54.             cmd1.Parameters.AddWithValue("@SubMenuName", lblsubmenu.Text);  
  55.             if (CHKR.Checked)  
  56.             {  
  57.                 cmd1.Parameters.AddWithValue("@SubMRead", 1);  
  58.             }  
  59.             else  
  60.             {  
  61.                 cmd1.Parameters.AddWithValue("@SubMRead", 0);  
  62.             }  
  63.             if (CHKW.Checked)  
  64.             {  
  65.                 cmd1.Parameters.AddWithValue("@SubMWrite", 1);  
  66.             }  
  67.             else  
  68.             {  
  69.                 cmd1.Parameters.AddWithValue("@SubMWrite", 0);  
  70.             }  
  71.   
  72.             if (CHKB.Checked)  
  73.             {  
  74.                 cmd1.Parameters.AddWithValue("@SubMBoth", 1);  
  75.             }  
  76.             else  
  77.             {  
  78.                 cmd1.Parameters.AddWithValue("@SubMBoth", 0);  
  79.             }  
  80.             cmd1.Parameters.AddWithValue("@SubUID", DrpUser.SelectedValue);  
  81.             cmd1.Parameters.AddWithValue("@SubRID", DrpRoles.SelectedValue);  
  82.             cmd1.Parameters.AddWithValue("@MainMenuID", HDMID.Value);  
  83.             con.Open();  
  84.             cmd1.ExecuteNonQuery();  
  85.             con.Close();  
  86.         }  
  87.     }  
  88.     ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('Data Saved Successfully');"true);  
  89. } 

I know it is a little bit difficult to understand this.

Here in this code I have 2 GridViews in which I am showing a menu and submenu(s); now I need to store the data as per the selection made.

Let's start with GridView1.

Gridview1 has the following 3 Checkboxes:

  1. Read
  2. Write
  3. Full control.

Here I am finding controls depending on Rowswise using a for loop.

  1. for (int i = 0; i < GridView1.Rows.Count; i++)       
  2.  CheckBox CHKR = (CheckBox)GridView1.Rows[i].FindControl("CHKR");     
  3.  CheckBox CHKW = (CheckBox)GridView1.Rows[i].FindControl("CHKW");     
  4.  CheckBox CHKB = (CheckBox)GridView1.Rows[i].FindControl("CHKB");     
  5.  Label lblMenuName = (Label)GridView1.Rows[i].FindControl("lblMenuName");     
  6.  HiddenField HDMID = (HiddenField)GridView1.Rows[i].FindControl("HDmenuID"); 

Inside Save you have seen this code that checks if the checkbox is checked then enter 1 else enter 2.

  1. if (CHKR.Checked)  
  2. {     
  3.      cmd.Parameters.AddWithValue("@MRead", 1);     
  4. }     
  5. else     
  6. {     
  7.     cmd.Parameters.AddWithValue("@MRead", 0);     
  8. } 

Now I have used gridview2 inside gridview1 and I need to find that.

Here I have found the control.

  1. GridView GV2 = (GridView)GridView1.Rows[i].FindControl("GridView2"); 

I have used 2 loops for finding the control inside 2 GridViews.

  1. for (int j = 0; j < GV2.Rows.Count; j++)         
  2.   CheckBox CHKRSUB = (CheckBox)GV2.Rows[j].FindControl("CHKRSUB");     
  3.   CheckBox CHKWSUB = (CheckBox)GV2.Rows[j].FindControl("CHKWSUB");     
  4.   CheckBox CHKBSUB = (CheckBox)GV2.Rows[j].FindControl("CHKBSUB");     
  5.   Label lblsubmenu = (Label)GV2.Rows[j].FindControl("lblsubmenu");     
  6.   HiddenField HDsubmenuID = (HiddenField)GV2.Rows[j].FindControl("HDsubmenuID"); 

Here is the final view after data selection.



Step 6

The last menu that you can see. [EditMenu.aspx]

This form is the same as [AssignRoleToUser.aspx]

This form will come in use when you have created a menu and saved it; you need to change the rights for some menus.

Here you must select:
  1. Role
  2. User Name.

 

After selecting the UserName dropdownlist you will see that the data related to that role is loaded.
 


Here you change the rights and just click on save it.

Step 7

The last menu Is Login Test. To test whether or not the menu we created is proper click that menu and it will redirect to the Login Page.

 


Here now I am showing you how to create a menu.

Let's add Master for Access rights and display the menu.

1. My Master Name is Main.Master.

Master contains a Literal Control for displaying a menu that will be generated.

Add I am also adding JavaScript Script Referance to it for making the menu Dynamic.

And .CSS for look and feel.

Finally I have added a Panel with the name PnlMain and inside that it contains ContainplaceHolder.

  1. <html xmlns="http://www.w3.org/1999/xhtml">     
  2. <head runat="server">     
  3.     <title></title>          
  4.     <link href="css/ddsmoothmenu.css" type="text/css" rel="stylesheet" />     
  5.     <script src="js/jquery.js" type="text/javascript"></script>     
  6.     <script src="js/ddsmoothmenu.js" type="text/javascript"></script>     
  7.     <asp:ContentPlaceHolder ID="head" runat="server">     
  8.     </asp:ContentPlaceHolder>     
  9. </head>     
  10. <body>     
  11.     <form id="form1" runat="server">     
  12.     <div>     
  13.         <asp:Literal ID="Literal1" runat="server"></asp:Literal>     
  14.         <script type="text/javascript">     
  15.            ddsmoothmenu.init     
  16.           ({     
  17.            mainmenuid: "smoothmenu2"//menu DIV id     
  18.           orientation: 'h'//Horizontal or vertical menu: Set to "h" or "v"     
  19.           classname: 'ddsmoothmenu'//class added to menu's outer DIV     
  20.                 //customtheme: ["#1c5a80", "#18374a"],     
  21.           contentsource: "markup" //"markup" or ["container_id","path_to_menu_file"]     
  22.            })     
  23.         </script>     
  24.         <asp:Panel ID="PnlMain" runat="server">     
  25.             <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">     
  26.             </asp:ContentPlaceHolder>     
  27.         </asp:Panel>     
  28.     </div>     
  29.     </form>     
  30. </body>     
  31. </html>   

Here I am showing code snippets for generating a menu.

  1. public void getmenu()     
  2. {     
  3.     if (Session["UserID"] == null)     
  4.     {     
  5.         Response.Redirect("Login.aspx");     
  6.    }     
  7.   else     
  8.   {     
  9.     con.Open();     
  10.     SqlCommand cmd = new SqlCommand("Usp_GetAllMenuofRole", con);     
  11.     cmd.CommandType = CommandType.StoredProcedure;     
  12.     cmd.Parameters.AddWithValue("@UserID1", Session["UserID"]);     
  13.     DataSet ds = new DataSet();     
  14.     SqlDataAdapter da = new SqlDataAdapter();     
  15.     da.SelectCommand = cmd;     
  16.     da.Fill(ds);     
  17.     StringBuilder ST = new StringBuilder();     
  18.     if (ds.Tables[0].Rows.Count > 0)     
  19.     {     
  20.          ST.Append("<div class='ddsmoothmenu' id='smoothmenu2'>");     
  21.          ST.Append("<ul>");     
  22.          for (int i = 0; i < ds.Tables[0].Rows.Count; i++)     
  23.          {     
  24.             string xid1 = ds.Tables[0].Rows[i]["MenuID"].ToString();     
  25.             string xid2 = ds.Tables[0].Rows[i]["MenuIDx"].ToString();     
  26.             string li = "<li style='z-index: 100;'>" + "<a href =" + ds.Tables[0].Rows[i]["MenuURL"].ToString() + "?MID1=" + xid1 + "&MID2=" + "M" + ">" + ds.Tables[0].Rows[i]["MenuName"].ToString() + "</a>";     
  27.            ST.Append(li);     
  28.            if (ds.Tables[0].Rows[i]["MenuID"].ToString() != null)     
  29.            {     
  30.                  SqlCommand cmd1 = new SqlCommand("Usp_Submenu", con);     
  31.                  cmd1.CommandType = CommandType.StoredProcedure;     
  32.                  cmd1.Parameters.AddWithValue("@userID", ds.Tables[0].Rows[i]["UID"].ToString());     
  33.                  cmd1.Parameters.AddWithValue("@MenuID", ds.Tables[0].Rows[i]["MenuID"].ToString());     
  34.                  DataSet ds1 = new DataSet();     
  35.                  SqlDataAdapter da1 = new SqlDataAdapter();     
  36.                  da1.SelectCommand = cmd1;     
  37.                 da1.Fill(ds1);     
  38.                 ST.Append("<ul style='top: 28px; visibility: visible; left: 0px; width: 118px; display: none;'>");     
  39.                 for (int j = 0; j < ds1.Tables[0].Rows.Count; j++)     
  40.                {     
  41.                    string yid1 = ds1.Tables[0].Rows[j]["MenuID"].ToString();     
  42.                    string yid2 = ds1.Tables[0].Rows[j]["subMenuIDx"].ToString();     
  43.                    if (ds1.Tables[0].Rows[j]["SubmenuName"].ToString() != null)     
  44.                    {     
  45.                         string lix = "<li>" + "<a href =" + ds1.Tables[0].Rows[j]["SubMenuURL"].ToString() + "?S1ID=" + yid1 + "&S2ID=" + "S" + ">" + ds1.Tables[0].Rows[j]["SubmenuName"].ToString() + "</a>" + "</li>";     
  46.                         ST.Append(lix);     
  47.                    }     
  48.             }     
  49.      }     
  50.         ST.Append("</ul>");     
  51.         ST.Append("</li>");     
  52.      }     
  53.         ST.Append("</ul>");     
  54.        ST.Append("</div>");     
  55.        Literal1.Text = ST.ToString();     
  56.    }     
  57. }   

In this code, I am designing the menu.

First I took:

  1. StringBuilder ST = new StringBuilder();  
  2. ST.Append("<div class='ddsmoothmenu' id='smoothmenu2'>");  
  3. ST.Append("<ul>"); 

Here I used a StringBuilder because I need to append the string as it is generated.

You have also seen that I have appended ( div , ul).

  1. SqlCommand cmd = new SqlCommand("Usp_GetAllMenuofRole", con);     
  2. cmd.CommandType = CommandType.StoredProcedure;     
  3. cmd.Parameters.AddWithValue("@UserID1", Session["UserID"]);     
  4. DataSet ds = new DataSet();     
  5. SqlDataAdapter da = new SqlDataAdapter();     
  6. da.SelectCommand = cmd;     
  7. da.Fill(ds);     
  8. StringBuilder ST = new StringBuilder();     
  9. if (ds.Tables[0].Rows.Count > 0)     
  10. {     
  11.     ST.Append("<div class='ddsmoothmenu' id='smoothmenu2'>");     
  12.     ST.Append("<ul>");     
  13.     for (int i = 0; i < ds.Tables[0].Rows.Count; i++)     
  14.     {     
  15.          string xid1 = ds.Tables[0].Rows[i]["MenuID"].ToString();     
  16.          string xid2 = ds.Tables[0].Rows[i]["MenuIDx"].ToString();     
  17.          string li = "<li style='z-index: 100;'>" + "<a href =" + ds.Tables[0].Rows[i]["MenuURL"].ToString() + "?MID1=" + xid1 + "&MID2=" + "M" + ">" + ds.Tables[0].Rows[i]["MenuName"].ToString() + "</a>";     
  18.          ST.Append(li);     
  19.       }                                
  20. } 

Then you can see that depending on use login I am getting UserID in Session.

I am passing session[UserID] to the Stored Procedure Usp_GetAllMenuofRole and getting all the menus from that procedure in the dataset and then using a loop to get all the rows in the dataset.

Now I am getting a menu Id depending on row and storing in xid1 and xid2.

MenuID contains the ID.

MenuIDx contains Type. “M”

  1. string xid1 = ds.Tables[0].Rows[i]["MenuID"].ToString();  
  2. string xid2 = ds.Tables[0].Rows[i]["MenuIDx"].ToString();  
  3. string li = "<li style='z-index: 100;'>" + "<a href =" + ds.Tables[0].Rows[i]["MenuURL"].ToString() + "?MID1=" + xid1 + "&MID2=" + "M" + ">" + ds.Tables[0].Rows[i]["MenuName"].ToString() + "</a>"

In string <li> I have passed a string that contains:

<li> </li> tags with achor tag inside it.
<a href =” URL ”> contains path and Passing Query String of MenuID and MenuType.
<a href =” URL ”> Here I am displaying Name of Menu </a>

After adding a Main Menu inside it I am adding a submenu with the same process.

Here is the code snippet:

  1. SqlCommand cmd1 = new SqlCommand("Usp_Submenu", con);     
  2. cmd1.CommandType = CommandType.StoredProcedure;     
  3. cmd1.Parameters.AddWithValue("@userID", ds.Tables[0].Rows[i]["UID"].ToString());     
  4. cmd1.Parameters.AddWithValue("@MenuID", ds.Tables[0].Rows[i]["MenuID"].ToString());     
  5. DataSet ds1 = new DataSet();     
  6. SqlDataAdapter da1 = new SqlDataAdapter();     
  7. da1.SelectCommand = cmd1;     
  8. da1.Fill(ds1);     
  9. ST.Append("<ul style='top: 28px; visibility: visible; left: 0px; width: 118px; display: none;'>");     
  10. for (int j = 0; j < ds1.Tables[0].Rows.Count; j++)     
  11. {     
  12.     string yid1 = ds1.Tables[0].Rows[j]["MenuID"].ToString();     
  13.     string yid2 = ds1.Tables[0].Rows[j]["subMenuIDx"].ToString();     
  14.     if (ds1.Tables[0].Rows[j]["SubmenuName"].ToString() != null)     
  15.     {     
  16.        string lix = "<li>" + "<a href =" + ds1.Tables[0].Rows[j]["SubMenuURL"].ToString() + "?S1ID=" + yid1 + "&S2ID=" + "S" + ">" + ds1.Tables[0].Rows[j]["SubmenuName"].ToString() + "</a>" + "</li>";     
  17.        ST.Append(lix);     
  18.     }    
  19. } 

I am passing UserId and Menuid and depending on it I am loading a submenu.

I have the same process as it is for the main menu.

After login you will see the menu that was generated.



Now the last part is how to apply Read and Write access to the pages.

For that I have written the following code that will read a Query string and that will pass something with a menu and submenu and load the rights from the table depending on it.

This code is only for the page load of the Master Page.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {         
  3.     if (!IsPostBack)     
  4.     {     
  5.         getmenu();     
  6.         string MenuType = Request.QueryString["MID2"];     
  7.         string subMenutype = Request.QueryString["S2ID"];     
  8.         string MenuID = Request.QueryString["MID1"];     
  9.         string subMenuID = Request.QueryString["S1ID"];     
  10.         if (MenuType != null)     
  11.         {     
  12.                SqlCommand cmd1 = new SqlCommand("Usp_GetAllRoles", con);     
  13.                if (MenuType != null)     
  14.                {     
  15.                    cmd1.Parameters.AddWithValue("@Menutype", MenuType);     
  16.                }     
  17.               else if (subMenutype != null)     
  18.               {     
  19.                    cmd1.Parameters.AddWithValue("@Menutype", subMenutype);    
  20.               }     
  21.               if (MenuID != null)     
  22.               {     
  23.                    cmd1.Parameters.AddWithValue("@ID", MenuID);     
  24.               }     
  25.               else if (subMenuID != null)     
  26.                {     
  27.                    cmd1.Parameters.AddWithValue("@ID", subMenuID);     
  28.                }     
  29.                cmd1.Parameters.AddWithValue("@RID", Session["RoleID"]);     
  30.                cmd1.Parameters.AddWithValue("@UID", Session["UserID"]);     
  31.                cmd1.CommandType = CommandType.StoredProcedure;     
  32.                SqlDataAdapter da1 = new SqlDataAdapter();     
  33.                da1.SelectCommand = cmd1;     
  34.                DataSet ds1 = new DataSet();     
  35.                da1.Fill(ds1);     
  36.                if (ds1.Tables.Contains("Table") == true)     
  37.                {     
  38.                    if (ds1.Tables[0].Rows.Count > 0)     
  39.                    {     
  40.                        if (ds1.Tables[0].Rows[0]["MRead"].ToString() == "1")     
  41.                        {     
  42.                            PnlMain.Enabled = false;     
  43.                        }     
  44.                        else if (ds1.Tables[0].Rows[0]["MBoth"].ToString() == "1")     
  45.                        {     
  46.                            PnlMain.Enabled = true;     
  47.                        }     
  48.                        else if (ds1.Tables[0].Rows[0]["MWrite"].ToString() == "1")     
  49.                        {     
  50.                            PnlMain.Enabled = true;     
  51.                        }     
  52.                        else     
  53.                        {     
  54.                            PnlMain.Enabled = false;     
  55.                        }     
  56.                }     
  57.            }     
  58.        }     
  59.    }  
  60. } 

I am using a panel to make the Page Read and Write.

Here is the menu that was generated.



Here is the form with write access control.

That is why we can enter data into this form.
 


Here is the home form which has read only rights.

Here you cannot enter the data, you can just view it.