Razor C# - Get data from database

Brandon Miller picture Brandon Miller · Feb 7, 2013 · Viewed 19.9k times · Source

I am using WebMatrix, I have created a database and put a table with a few rows of data. I can connect to it and get the data with the WebGrid, but it only provides a way to output the data using a table.

Here is my code for 'shows.cshtml':

@{
    var db = Database.Open("TVPort");
    var shows_data = db.Query("SELECT * FROM shows");
    var shows_grid = new WebGrid(source: shows_data);
}

What I would like to be able to do is enumerate through each row returned by the query, and do whatever I want with the value of each column. But the WebGrid only allows you to output the data in a table. I just started using WebMatrix and the Razor syntax today.

Also (side-question here, didn't think it's enough to be its own question), is there any way to make a C# code file for my 'shows.cshtml' page? In Visual Web Developer 2010 each page has a 'page.aspx' file and a 'page.aspx.cs' where the 'page.aspx.cs' file lets you make custom functions to be used in the page, or perform a task when the page loads. Is there similar behavior using CSHTML in WebMatrix? Or is all of the code supposed to be inline with the actual page?

Answer

Brandon Miller picture Brandon Miller · Feb 7, 2013

Found the answer at Working With Data : ASP.net

@foreach(var row in db.Query("SELECT * FROM shows")) {
  <em>@row.title</em> - Cast: @row.cast
}