1

I have a Microsoft Access Database (.accdb) full of values that I wish to display in a table on my .cshtml razor page. I need to open the connection and then make the table with the values.

I think that the table would be something like this:

<table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Address</th>
                <th>Address 2</th>
                <th>Field of Work</th>
            </tr>
        </thead>

       <tbody>
            @foreach (var row in _____.Query(____))
            {
                <tr>
                    <td>@row.name</td>
                    <td>@row.address</td>
                    <td>@row.address2</td>
                    <td>@row.field</td>
                </tr>
            }
        </tbody>
  </table>

, but I have not been able to open the connection correctly.

Advice please?

4

1 回答 1

3

If you are using Access, you should put the database file in App_Data and specify a connection string in your web.config file:

<connectionStrings>
    <add name="MyConnection" 
      connectionString="Provider="Microsoft.ACE.OleDb.12.0;Data Source=|DataDirectory|MyDatabase.accdb;" 
      providerName="System.Data.OleDb" />
</connectionStrings>

|DataDirectory| is a special short-cut that resolves to the location of the App_Data folder.

When you use the Database helper, you pass in the name of the connection string:

var db = Database.Open("MyConnection");
var data = db.Query("SELECT * FROM MyTable");
...
...
<tbody>
    @foreach (var row in data){
        <tr>
            <td>@row.name</td>
            <td>@row.address</td>
            <td>@row.address2</td>
            <td>@row.field</td>
        </tr>
    }
</tbody>

However, if you are using MVC, the database opening and querying should not happen in the view. You should do that in the controller, or better yet, in a data layer. Alternatively, you can look at ASP.NET Web Pages where the data access code does belong in the view: http://asp.net/web-pages.

于 2013-10-06T07:26:11.413 回答