问题
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?
回答1:
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
}
回答2:
You are going around this the wrong way! The MVC pattern has its strengths in separating the data-logic from the actual content and right now you are retrieving new data in the View (which doesn't leave much control to the Controller)!
Have a look at 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 both your questions). It might seem a bit overdone if you used PHP and wrote every query directly in the same page before, but trust me, the code you create will be cleaner and a lot easier to maintain with ASP.Net MVC.
回答3:
With reference to your side-question, I would say that using the Razor framework you cannot have a code-behind file. It mixes server-side code and client-side code together. If you want to have a code-behind file then you could use Asp.net Web Pages without the razor view engine on Visual Studio.
回答4:
For the side question i believe the @function{"insert code inside this block"} will allow you to create your custom functions inside your page. Hope this helps anyone else who may have similar question and end up here. Believe it or not there are some great documentation on how to get started @ http://www.asp.net/get-started. Just go through the tutorials.
来源:https://stackoverflow.com/questions/14744595/razor-c-sharp-get-data-from-database