X
HOME HTML CSS JAVASCRIPT SQL PHP JQUERY XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

ASP.NET Web Pages - Adding a Database


Learn ASP.NET Web Pages by building a web site from scratch.

Part III: Adding a Database.


What We Will Do

In this chapter we will:

  • Create a web page to list data from a database

Displaying Data from Database

With Web Pages, you can easily display data from a database.

You can connect to an existing database, or create a new database from scratch.

In this example we will connect to an existing SQL Server Compact database.

If you want to learn how to create a database for your web, please go to the chapter Web Database.


Adding a Customers Page

In the "DemoWebPages" folder, create a new CSHTML file named "Customers.cshtml".

Replace the code in the file with the code from the example below:

Customers.cshtml

@{Layout = "Layout.cshtml";
var db = Database.Open("Northwind"); 
var query = db.Query("SELECT CompanyName,City,Country FROM Customers"); 
}

<html> 
<body> 
<h1>Customers</h1> 
<table> 
<tr>
<th>Name</th> 
<th>City</th> 
<th>Country</th> 
</tr>
@foreach(var row in query)
{

<tr> 
<td>@row.CompanyName</td> 
<td>@row.City</td> 
<td>@row.Country</td> 
</tr> 
}
</table> 
</body> 
</html>

Run example »


Database Connection

The Database.Open(name) method will connect to a database in two steps:

First, it searches the application's App_Data folder for a database that matches the name parameter without the file-name extension.

If no file is found, it looks for a "connection string" in the application's Web.config file.

(A connection string contains information about how to connect to a database. It can include a file path, or the name of an SQL database, with full user name and password)

This two-step search makes it possible to test the application with a local database, and run the application on a web host using a connection string.



Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates FREE Website Templates Free HTML Templates

SHARE THIS PAGE

facebook