(1) first, create an MVC project, preferably mvc1.0 or later. (2) I didn't reconfigure route resolution in this demo, and used the default route resolution address of the MVC project. If anyone is interested, add a default route! (3) I have a database named database1.mdf, which contains a news table. (4) Right-click the models folder and choose models to add a new project: You can set the name as needed. Here is test. edmx, and then click Add. Next step: Here, we can click "create connection" to select the desired database. The following is the name of the connection string stored in webconfig. We can modify it by ourselves. Next step: Select the database object in the model. Click Finish. In solution manager, we can see the models Folder: In this way, our database connection is complete. The following describes how to use the database. (5) Add the Controller class file named newscontroller. CS. I added the following method in newscontroller: Public actionresult list () {testentities DB = new testentities (); // instantiate a data object. VaR model = dB. News. tolist (); // call the return view (model) of the news table in the database; // return a model} (6) Right-click list () and select add view. Select Add. (7) In this way, we can see in the Views file: Add a news folder and a list. aspx file. Open the list. aspx file. In the first line, we need to add: System. Web. MVC. viewpage <ienumerable <mvcapplication1.models. News> In this way, we can get the corresponding data model. On the View Interface, I have the following layout: <H2>
List </H2>
<Table>
<Tr>
<TH>
Title
</Th>
<TH>
Author
</Th>
</Tr>
</Table>
<% Foreach (VAR item in Model)
{%>
<Table>
<Tr>
<TD> <a href = "/home/index/<% = html. encode (item. news_id) %> "> <% = html. encode (item. news_title) %> </a>
</TD>
<TD>
<% = Html. encode (item. news_author) %>
</TD>
</Tr>
</Table>
<% }%> I added a link to the news title to obtain the news ID. (8) In this way, we can use database instances in the MVC project. Let's take a look: After clicking the title, we will jump: the last parameter is the news ID. In this way, we can display the database data.