Novice question:
I have an SQLite db with some randomg movie info that I'm reading data from and adding said data to a view. However, right now it's going through the table and only adding the last record to the view. How do I add each record as the SQLiteDataReader is through the table instead of just the last record in the table?
This is my current controller code:
public ActionResult dbView()
{
string cs = "Data Source=" + Environment.CurrentDirectory + "\\example.db";
using (SQLiteConnection con = new SQLiteConnection(cs))
{
con.Open();
string stm = "SELECT * FROM Movie";
using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
{
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
ViewBag.movie = rdr["MovieId"];
ViewBag.title = rdr["title"];
ViewBag.rating = rdr["rating"];
ViewBag.image = rdr["image"];
}
}
}
var image = "data:image/png;base64," + Convert.ToBase64String(ViewBag.image);
ViewBag.image = image;
con.Close();
}
return View();
}
My view code:
<div class="col-md-4">
<table style="width: 100%" border="1">
<tr>
<th>Title</th>
<th>Rating</th>
</tr>
<tr>
<td>@ViewBag.title</td>
<td>@ViewBag.rating</td>
</tr>
</table>
<img src="@ViewBag.image" style="width: 300px"/>
</div>
UPDATE: Here's where I'm currently at:
public List<Movie> Movies { get; set; }
public ActionResult dbView()
{
string cs = "Data Source=" + Environment.CurrentDirectory + "\\example.db";
using (SQLiteConnection con = new SQLiteConnection(cs))
{
var listOfMovies = new List<Movie>();
con.Open();
string stm = "SELECT * FROM Movie";
using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
{
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
listOfMovies.Add(new Movies
{
MovieID= int.Parse(reader["EmployeeId"].ToString()),
Title= reader["Title"].ToString(),
Rating= reader["Rating"].ToString(),
});
}
rdr.Close();
Movies = listOfMovies;
}
}
con.Close();
}
return View(Movies); // this says "Class name is not valid"
}
}
And my model:
public class Movie
{
Public int MovieID {get;set;}
Public String Title {get;set;}
Public int rating {get;set;}
Public Byte Image {get;set;}
}
Added to the view:
@foreach (var item in Movies) // this says "cannot resolve symbol Movies"
{
<tr>
<td>@ViewBag.title</td>
<td>@ViewBag.rating</td>
</tr>
}