Differentiate list of items shown in the View using "Individual User Account" Asp.Net MVC 5

Asked

Viewed 203 times

0

I don’t have much practice in programming and am creating a system of registering items like movies, books, games, etc. for a college job. The problem is that I need to use a user manager system so that in the index view of each type of item show only what the user registers, for example:

João registered in his list of films "Os Infiltrados" and "Clube da Luta"; José registered in his list of films "Harry Potter" and "The Lord of the Rings".

When João logs in, he should only show the films he has registered, in the same way that when José logs in, he should only show the films he has registered.

I created the project using "Individual User Account".

Someone would know to help me?

Thank you!

1 answer

2


Projects with "Individual User Accounts" come with ASP.NET Identity installed by default. To do what you want, your entities should be modeled containing the following:

public class Filme
{
    [Key]
    public int FilmeId { get; set; } // Essa é a chave primária.
    public String UsuarioId { get; set; } // Essa é a chave estrangeira, obrigatória.

    // Coloque o resto dos campos aqui

    public virtual ApplicationUser Usuario { get; set; } // Esta linha é a mais importante, 
                                                         // determinando que um filme pertence
                                                         // a um usuário.
}

When saving a record, register the current user as the "owner" of the record.

filme.UsuarioId = User.Identity.GetUserId();

When reading logs, select by the logged in user:

var usuarioId = User.Identity.GetUserId();
var filmes = db.Filmes.Where(f => f.UsuarioId == usuarioId).ToList();

An elegant way to bring objects linked to the user is to change the class ApplicationUser to the following:

public class ApplicationUser: IdentityUser
{
    // Coloque aqui campos que você quer que o usuário tenha.

    public virtual ICollection<Filme> Filmes { get; set; }
}

In the Controller do so:

var usuarioId = User.Identity.GetUserId();
var usuario = db.Usuarios.Include(u => u.Filmes).FirstOrDefault(u => u.UsuarioId == usuarioId);

var filmes = usuario.Filmes.ToList();
  • Thanks man, I got to understand the process and I’m applying in my project. It would be more specific where I apply the "Read records" part and which method I put the Controller part into. Thank you!!

  • "Read records" usually stays within a Action Index or similar. I don’t know if you’re using Scaffolding or doing everything manual, but Visual Studio generates all this cliché code for you. The Controller also goes in the same Action Index. I just did it as an alternative approach.

  • I’m using Scaffolding yes. All right, I’ll try here... Thanks so much for the help!!

Browser other questions tagged

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