ASP NET Core MVC how to display data from SQL table in List Razor Template by UserID foreign key

I have a Identity tables like AspNetUsers and others. I created migration Files with foreign key UserID to Id from AspNetUsers table for save files in Files table with logged in user Id. But in my FileManager View I see all files from Files table, but I need to display files only with UserID = Id from AspNetUsers (I mean with Id of logged in user). How Can I do it?

I think I need to edit some information in FileManager function but I’m not confident in it. If you need more code from the controller or other files in my ASP.NET Core project I can get it to you.

This code from my WorkSpaceController that has other functions with uploading new file and other things, but this FileManager function get data from context in var and displays on the FileManagerView:

private readonly TextCloudContext Context;

public IActionResult FileManager()
{
    var items = Context.Files.ToList();
    return View(items);
}

This is TextCloudContext code:
namespace TextCloud.Data
{
    public class TextCloudContext : IdentityDbContext<TextCloudUser>
    {
        public TextCloudContext(DbContextOptions<TextCloudContext> options) : base(options)
        {
        }

        public DbSet<File> Files { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }
}

Hope you can help me guys! Also, files dbo has UserId foreign key that references to Id in AspNetUsers table. I create Files table using Add-Migration command and Update-Database, so it works well and store files with current user Id, but I need to display information in ListRazorView (FileManager.cshtml) only for current logged in user.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

in my FileManager View I see all files from Files table, but I need to display files only with UserID = Id from AspNetUsers (I mean with Id of logged in user). How Can I do it?

To achieve the above requirement, you can try to call UserManager.GetUserId(ClaimsPrincipal) method to get user’s id, then query files based on retrieved user id, like below.

//get user id of current logged-in user 
var currentUserId = _userManager.GetUserId(User);

var items = Context.Files.Where(f => f.UserID == currentUserId).ToList();
return View(items);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x