Here’s a code sample showing a quick and easy way to loop through the results of a SQL query and display them on a web page in a list.
@{ var db = Database.Open("YourDatabase"); var ListDataItems = db.Query("SELECT SomeField FROM SomeTable"); } <!DOCTYPE html> <html lang="en"> <meta charset="utf-8" /> <head> <meta charset="utf-8" /> <title>ForEach Query Test Page</title> </head> <body> <ul> @foreach(var ListItem in ListDataItems){ <li>@ListItem.SomeField</li> } </ul> </body> </html>
This is pretty basic but let’s break it down.
In this example I have an existing database in my project’s /App_Data/ folder named “YourDatabase.sdf” (it’s a SQL CE database). I reference that database in line 2 and then run my query in line 3. The results of that query are placed into a recordset stored in the ListDataItems variable also defined on line 3.
Most of the rest is basic HTML but on line 14 I start a look that iterates through each item in ListDataItems and puts the rows – one at a time – into the ListItem variable.
On line 15 I reference the row (using ListItem) and also the specific field I want to display – SomeField in this case. I could have easily had multiple items returned per row in my query (line 3) and in that case I would have been able to reference whichever, or multiples, using their specific field name.
Line 16 just closes out the code block for the loop.