MVC Get a row of data and display them in a view

Alex_D

Member
Joined
Dec 26, 2019
Messages
6
Programming Experience
Beginner
Beginner problem:

I have some data in a database, and I select one row from it using the code line:

C#:
var ItemInDb = _context.ItemInDb.Find(id);

Whenever I select entire table, I use ToList() at the end of the line instead of Find(id), use ViewBag and then I can use foreach loop to display the table.

However in the above case I can not use the same method. I can also see that ItemInDb does actually contain all the data from corresponding row.

Is there a direct way to put this data in corresponding view. Any help is highly appreciated
 
If you follow most of the MVC + Entity Framework tutorials, you will see this as one of the 'R' in the CRUD operations that is usually taught. Which tutorial are you following?
 
If you follow most of the MVC + Entity Framework tutorials, you will see this as one of the 'R' in the CRUD operations that is usually taught. Which tutorial are you following?
I am using several tutorials and I find different solutions for transferring the table to view. However, having problems and can not fit these solutions to single row.
 
Basically when you find by ID, you'll only get back a single object. In your Razor page, instead of binding to a list of objects, you only bind to a single object.

See some of the examples in the cheatsheet regarding @model .
 
Don't call ToList and don't use a foreach loop. When you tell VS to create a view to add or edit a record, it will create a template for you that has a singular model and binds the properties of that model to individual controls. It's generally only a Index view that has a list model and uses a loop. I find it hard to believe that you are using a tutorial that wouldn't teach that.
 
I wonder if our OP is truly following a tutorial, or if he is Googling for stuff and just jumping into the middle of one or more tutorials instead of following a single tutorial end-to-end.
 
Back
Top Bottom