简体   繁体   中英

MVC show data based on current user

I have a table in MVC with many to many relationship, inside the table is { SubjectID,UserID,LevelID} now how to filter the result of the table i want the current user is logged in can only see the the SubjectID,LevelId that belongs to the current User. Any Simple Idea to make this Work? Thanks and Appreciate your response..

Controller:

    [Authorize(Roles ="Teacher")]
    public ActionResult Index()
    {
        var subjectTeachers = db.SubjectTeachers.Include(s => s.Levels).Include(s => s.Subjects).Include(s => s.Users);
        return View(subjectTeachers.ToList());
    }

Model:

 [Key]
    public int SubTech { get; set; }

    public int SubjectID { get; set; }
    public virtual Subject Subjects { get; set; }

    public int UserID { get; set; }
    public virtual User Users { get; set; }


    public int LevelID { get; set; }
    public virtual Level Levels { get; set; }

Since you don't want to use ASP.NET Identity, you can try replacing your line by:

[Authorize(Roles ="Teacher")]
public ActionResult Index()
{
    var subjectTeachers = db.SubjectTeachers.Include(s => s.Levels).Include(s => s.Subjects).Include(s => s.Users).Where(u => u.UserID == id);
    return View(subjectTeachers.ToList());
}

You should pass the UserID from either session or through the controller and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM