Im currently trying to make a deck builder. I want the Deck form to show certain cards that a single user has and not the total list of all cards in database. I currently have a drop down list of all cards in the database the cards have another property to it that has the UsersId when it was added to the collection. I want the drop down list to on pull ones with that users Id.
Here is the controllers action. I'm assuming what I need to do is right here where I get the whole list of cards.
public ActionResult New()
{
var cards = _context.Cards.ToList();
var viewModel = new DeckFormViewModel
{
Cards = cards
};
return View("DeckForm", viewModel);
}
Here is the form.
@using (@Html.BeginForm("AddCard", "Deck"))
{
<div >
@Html.LabelFor(m => m.Deck.CardsId)
@Html.DropDownListFor(m => m.Deck.CardsId, new SelectList(Model.Cards, "Id", "Name"), "Choose Card", new { @class = "form-control" }, )
</div>
}
This just shows every card added to database regardless of the userId
CodePudding user response:
You're telling it to get all of the cards:
_context.Cards.ToList()
_context.Cards
refers to the Cards table. It will load the whole table unless you tell it otherwise.
To filter, use .Where()
, for example:
var cards = _context.Cards.Where(c => c.UserId == userId).ToList();
This assumes there's a column in the Cards table called UserId
, and that you have a variable called userId
with the current user's username.
There more information about querying data using Entity Framework here: Querying Data