Skip to main content

Command Palette

Search for a command to run...

Filter data in an MVC application for a specific user

Published
2 min read
Filter data in an MVC application for a specific user
R

I am a recent graduate at the beginning of my software development career. I enjoy documenting my learnings through my blogs

I created a recipe blog in ASP.NET MVC as part of a college project. This application used Entity Framework to retrieve and store data. As part of this, I had a list of all recipes and also a list of favourite recipes that a user can save and remove.

I encountered a problem as part of this implementation. The favourites list was displaying the saved recipes of every user, whereas I wanted only the logged-in user’s recipes to be displayed.

For this, I needed to figure out how I could filter by the user ID and only display the relevant results to the user.

To solve this issue I was facing I decided to use LINQ to filter by the user’s ID in the favourites database. You will need the using statement using Microsoft.AspNet.Identity; to retrieve the userId because this is stored in a separate database on the local server. To get this to work I needed to create a variable to store the user id as the GetUserId() method does not work within the query. I then used this variable in the query to compare the user id’s.

See the code below for an example…

using Microsoft.AspNet.Identity;

public ActionResult Index()
        {
            var userId = User.Identity.GetUserId();

            var userFavourites = db.Favourites
                .Where(f => f.UserID == userId)
                .ToList();

            return View(userFavourites);
        }

Using LINQ to filter the data allowed me to only display the results of a specific user. I could also use this method in other areas of my project such as deleting recipes from the database, so if a user added a recipe to the blog only they would be able to delete that recipe when logged in.

This method is beneficial if you want to give access to certain users to view only specified data.