Razor C # - Get data from a database

I use WebMatrix, I created a database and placed a table with several rows of data. I can connect to it and get data using WebGrid , but it only provides a way to output 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 do is to list each row returned by the query and do whatever I want with the value of each column. But WebGrid allows you to output data to a table. I just started using WebMatrix and Razor syntax today.

Also (side question here, didn't think it was enough to be his own question), is there a way to make a C # code file for my show.cshtml page? In Visual Web Developer 2010, each page has a page.aspx and a page.aspx.cs file, where the page.aspx.cs file allows you to create custom functions on the page or perform a task when the page loads. Is there any similar behavior using CSHTML in WebMatrix? Or should all the code be embedded with the actual page?

+4
source share
4 answers

Found an answer to Working with data: ASP.net

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

You will get around this wrong! The MVC template has its own strengths in separating data logic from actual content, and now you get new data in the view (which does not leave much control over the controller)!

Check out http://www.asp.net/mvc for some great tutorials on how to use ASP.Net MVC and how to structure your classes and files (it will answer your questions). This may seem a little exaggerated if you used PHP and wrote each request every time on the same page, but believe me, the code you created will be cleaner and much easier to maintain with ASP.Net MVC.

0
source

As for your side question, I would say that using the Razor framework you cannot have a code file. It mixes server side code and client code together. If you want to have a code file, you can use Asp.net web pages without a razor viewer mechanism in Visual Studio.

0
source

For the side question, I believe that @function {"insert code inside this block"} will allow you to create your own custom functions inside your page. Hope this helps anyone who might have a similar question, and ultimately. Believe it or not, there is excellent documentation on how to get started @ http://www.asp.net/get-started . Just browse through the tutorials.

0
source

All Articles