How to pass parameters to the _Layout.cshtml view in Asp.Net projects

Asked

Viewed 1,135 times

0

Hello, seeing as I have one Area control panel my layout basically changes only the center with the views, but I want to put functionalities in the part where the _Layout.cshtml, and for such functions I need to access the object of the logged in person. How do I do this?

  • I use a Usuariorepositorio class where I have a Static method called Getusuariologated() that checks if the user is logged in and returns this user’s data to me. How you are doing your authentication?

  • put as resposa and also code so I can understand better?

1 answer

2


In my projects I use a Class static calling for UsuarioRepositorio As follows below:

public class UsuarioRepositorio
    {
        public static bool AutenticarUsuario(string login, string senha)
        {
            var context = new NewsContext();

            var user = context.Users.SingleOrDefault(u => u.Login == login && u.Status);

            if (user == null)
            {
                return false;
            }
            if (!Crypto.VerifyHashedPassword(user.Senha, senha))
            {
                return false;
            }

            FormsAuthentication.SetAuthCookie(user.Login, false);

            return true;
        }

        public static User GetLogedUser()
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated) return null;

            var login = HttpContext.Current.User.Identity.Name;

            var context = new NewsContext();

            if (string.IsNullOrEmpty(login))
            {
                return null;
            }

            var user = context.Users.SingleOrDefault(u => u.Login == login && u.Status);
            return user;
        }

        public static void LogOf()
        {
            FormsAuthentication.SignOut();
        }
    }

Where I have 3 methods, AutenticarUsuario, GetLogedUser and LogOf.

When I need to do something I need to get the user information logged in, for example: Print the User name logged in to the Admin Panel.

I wear it like this:

@using Projeto.Repositorio

<label>Bem vindo: @UsuarioRepositorio.GetLogedUser().Nome</label>

Works perfectly for me.

And you can use in other ways, such as checking if the user has any property or Role which defines it as Admin and print only the allowed menu items to the rule where it is located.

Follows link of the article where I learned to use these methods.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.