Friday 1 February 2013

How to create database driven role base menu in asp.net with c#


For my new task, I wanted to create role based menu where menu options will be change as per user role.
        The only condition was the first menu option 'Home' will remain same for all users with different page url. Like if user is admin then 'Home' link contain default admin page but if user is normal user then on the same 'Home' link default page will be show as per user need.

I have google and found many links but didn't get any role base menu link. So finally, with little trick and twist, I have created this menu which I wanted to share with you guys.

Firstly, create a method GetRolebaseMenuDetail(int UserID) to read data from database to dataset.For reading data , I have used stored procedure which return menu data.Pass User ID as parameter in stored procedure.

public DataSet GetRolebaseMenuDetail(int UserID)
        {

            DataSet dsTemp = new DataSet();
            DataRelation relation;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand comm = new SqlCommand())
                {
                    comm.Connection = conn;
                    comm.CommandText = "spMenuDetailsRoleWise";
                    comm.CommandType = CommandType.StoredProcedure;
                    comm.Parameters.AddWithValue("@UserID", UserID.ToString());
                    SqlDataAdapter da = new SqlDataAdapter(comm);
                    da.Fill(dsTemp);
                    da.Dispose();
                }
            }

            dsTemp.DataSetName = "Menus";
            dsTemp.Tables[0].TableName = "Menu";
            dsTemp.Tables[1].TableName = "RoleDetail";
 
   //set parent and child relationship between menu data
            relation = new DataRelation("ParentChild", dsTemp.Tables["Menu"].Columns["MenuID"], dsTemp.Tables["Menu"].Columns["ParentID"], false);
            relation.Nested = true;

            dsTemp.Relations.Add(relation);
            return dsTemp;
        }

After reading data in dataset , now bind Menu control

public void PopulateRolebaseMenu(int UserID,string HomePageURL)
        {
            DataSet dsMenu = GetRolebaseMenuDetail(UserID);
       
            foreach (DataRow masterRow in dsMenu.Tables["Menu"].Rows)
            {
                MenuItem masterItem = null;
                if (Convert.ToInt32(masterRow["ParentID"]) == 0)
                {
                    masterItem = new MenuItem((string)masterRow["Menu_Name"]);
                    masterItem.ToolTip = masterRow["Tooltip"].ToString();
                    if (masterRow["Menu_Name"].ToString() == "Home")
                    {
                        masterItem.NavigateUrl = HomePageURL;
                    }
                    else
                        masterItem.NavigateUrl = masterRow["URL"].ToString();
                    Menu1.Items.Add(masterItem);
                }

                foreach (DataRow childRow in masterRow.GetChildRows("ParentChild"))
                {
                    MenuItem childItem = new MenuItem((string)childRow["Menu_Name"]);
                    childItem.NavigateUrl = childRow["URL"].ToString();
                    childItem.ToolTip = childRow["Tooltip"].ToString();
                    masterItem.ChildItems.Add(childItem);
                }
            }      
        }


Here , first parameter is the User's Id who just login and second is the default page url which should be open on default 'Home' option , as per User role.
Happy Coding !!!! :-)




3 comments:

  1. Hello Sir, Could you post a screen shot of stored procedure and sql tables bcz u had given coding only that i got confusion where it will check the role name and display the menu.
    thank u

    God Bless U

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. hy i have url in database but i want to change this for user another url which is logical not a physical

    ReplyDelete