Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hola, me pueden ayudar, necesito hacer un menú dinámico webForm en asp.net, y que lo muestre dependiendo del rol o perfil de cada usuario.


Translation:
Hello, I can help, I need to make a dynamic menu WebForm in ASP.net, and show it depending on the role or profile of each user.

Not much, I followed an article published on this page, but I did not understand much

What I have tried:

no mucho, seguí un articulo publicado en esta misma pagina, pero no entendí mucho
Posted
Updated 31-Jan-18 4:25am
v2

 
Share this answer
 
Quote:
Not much, I followed an article published on this page, but I did not understand much

Articles are written by site members, the best to contact the author is the forum on bottom of article page.
 
Share this answer
 
---Primero debe crear estas tablas para el manejo de menu
---- en estas estan las opciones que existen en todo el menu.
CREATE TABLE [dbo].[menu_opciones] (
[MenuId] INT IDENTITY (1, 1) NOT NULL,
[padremenu] INT NOT NULL,
[hijomenu] NVARCHAR (10) NOT NULL,
[descripcion] NVARCHAR (50) NOT NULL,
[url] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_YA_EXISTE_MENU] PRIMARY KEY CLUSTERED ([hijomenu] ASC)
);

-- en esta tabla insertas las opciones del menu que corresponden al perfil.
CREATE TABLE [dbo].[menu_perfiles_opciones] (
[codperfil] NVARCHAR (20) NOT NULL,
[hijomenu] NVARCHAR (10) NOT NULL
CONSTRAINT [pk_perfil_y_opcion_ya_existen] PRIMARY KEY CLUSTERED ([codperfil] ASC, [hijomenu] ASC));

--- aqui los usuarios,.... en este caso usaras la tabla que tienes donde insertas los usuarios. debe estar la columna "Perfil "

CREATE TABLE [dbo].[usuarios_app] (
[usuario] NVARCHAR (80) NOT NULL,
[passw] NVARCHAR (20) NOT NULL,
[codperfil] NVARCHAR (20) NOT NULL,
PRIMARY KEY CLUSTERED ([usuario] ASC));


insert into menu_opciones values (0,'0.0','Inicio','~/Index.aspx'); --1
insert into menu_opciones values (0,'2.0','Menu administrador','#'); -- 2
insert into menu_opciones values (2,'2.1','Opcion de administrador','~/pagina2.aspx'); --3
insert into menu_opciones values (0,'4.0','Menu Usuario','#'); --4
insert into menu_opciones values (4,'4.1','Opcion de Usuario','~/pagina2.aspx'); --5


insert into menu_perfiles_opciones values ('ADMIN','0.0');
insert into menu_perfiles_opciones values ('USUARIO','0.0');

insert into menu_perfiles_opciones values ('ADMIN','2.0');
insert into menu_perfiles_opciones values ('ADMIN','2.1');
insert into menu_perfiles_opciones values ('ADMIN','4.0');
insert into menu_perfiles_opciones values ('ADMIN','4.1');


insert into menu_perfiles_opciones values ('USUARIO','4.0');
insert into menu_perfiles_opciones values ('USUARIO','4.0');



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>



<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Menú</title>


    <form id="form1" runat="server">
    <div>
    <asp:Menu ID="Menu1" runat="server" Orientation="Horizontal" BackColor="#E3EAEB" DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="Medium" ForeColor="#666666" StaticSubMenuIndent="10px">
        <DynamicHoverStyle BackColor="#666666" ForeColor="White" />
        <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
        <DynamicMenuStyle BackColor="#E3EAEB" />
        <DynamicSelectedStyle BackColor="#1C5E55" />
        <StaticHoverStyle BackColor="#666666" ForeColor="White" />
        <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
        <StaticSelectedStyle BackColor="#1C5E55" />
 

    </div>
    </form>






y codido 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class Default2 : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = this.TraeOpcionesDeMenu(0);
            CargaMenu(dt, 0, null);
        }
    }

    private DataTable TraeOpcionesDeMenu(int parentMenuId)
    {
        string query = "SELECT *FROM menu_perfiles_opciones as mpo,menu_opciones as mo,usuarios_app as ua where  MPO.hijomenu = MO. hijomenu and ua.codperfil = mpo.codperfil and mo.padremenu = @MenuIdPadre  and ua.usuario=@User";
        string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; // ConnectionString sera el nombre de tu conexion. 
        using (SqlConnection con = new SqlConnection(constr))
        {
            DataTable dt = new DataTable();
            using (SqlCommand cmd = new SqlCommand(query))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Parameters.AddWithValue("@MenuIdPadre", parentMenuId);
                    cmd.Parameters.AddWithValue("@User", Page.User.Identity.Name);

                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                }
            }
            return dt;
        }
    }

    private void CargaMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem)
    {
        string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
        foreach (DataRow row in dt.Rows)
        {
            MenuItem menuItem = new MenuItem
            {
                Value = row["MenuId"].ToString(),
                Text = row["descripcion"].ToString(),
                NavigateUrl = row["url"].ToString(),
                Selected = row["url"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
            };
            if (parentMenuId == 0)
            {
                Menu1.Items.Add(menuItem);
                DataTable dtChild = this.TraeOpcionesDeMenu(int.Parse(menuItem.Value));
                CargaMenu(dtChild, int.Parse(menuItem.Value), menuItem);
            }
            else
            {
                parentMenuItem.ChildItems.Add(menuItem);
            }
        }
    }




}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900