daniel_aren
daniel_aren

Reputation: 1924

How can I get data which equals a specific user in my MVC?

I am trying to show different information from the database on my website depending on which user is logged in. I have just begun with MVC (have done a couple of tutorials and can see information through my views on webpage.) Now I want to filter data on the user who is logged in. I am thinking a where clause somewhere. I am thinking in this controller where the context gets the data from db.

But how? Or is this the wrong place? Please tell me if you need some more info..

I am trying with db.Contacts.ToList().Where(), but I don´t get access to UserName here..

private ApplicationDbContext db = new ApplicationDbContext();

// GET: 
public ActionResult Index()
{
    return View(db.Contacts.ToList());
}

Upvotes: 0

Views: 263

Answers (1)

mfanto
mfanto

Reputation: 14418

What does your Contacts class look like? Presumably there's a foreign key on it pointing to the user for whom the contacts belong to. Something like:

public class Contact
{
    public int ContactId { get; set; }
    public int UserId { get; set; } // the Id of the User the contact belongs to
    public string Name { get; set; }
    public string Phone { get; set; }
}

You can then filter on that user id:

return View(db.Contacts.Where(c => c.UserId == CurrentUserId).ToList());

You can get the current user id by looking at the User.Identity.Name property in your controller. Assuming when the user authenticated you stored their username

public ActionResult Index()
{
    User current = db.Users.Single(u => u.Username == User.Identity.Name);

    return View(db.Contacts.Where(c => c.UserId == current.Id).ToList());
}

To make things easier, I put the CurrentUserId call in a base controller, so that any action can just reference CurrentUserId and be on its way.

Upvotes: 2

Related Questions