(1) First we create an MVC project, of course, preferably the mvc1.0 version.
(2) My demo, no reconfiguration routing resolution, using the default routing resolution address of the MVC project. Of course, if anyone is interested, you can add a default route yourself!
(3) I have a database named Database1.mdf that contains a news form.
(4) Then we right-click on the Models folder, Models to add a new item, select:
The name can be casually picked up. I'm here called TEST.EDMX, and then click Add.
Here we can click the new connection, to select the database we want, the bottom is the webconfig stored in the connection string name, we can modify our own.
This selects the database objects in the model. then click Finish.
In Solution Manager we can see under the Models folder:
So our database connection is complete. The following is how to use the database.
(5) Below we add controller class file, named NewsController.cs
I added the following methods in Newscontroller:
Public ActionResult List ()
Testentities db = new testentities ();//Instantiate the data object.
var model = db. News.tolist ()//Call the news table in the database
return View (model);//Returns a model
(6) Then we right-click the list () and select Add View.
(7) So we will see in the views file:
One more news folder and List.aspx file.
Open list.aspx file, in the first line we need to add:
System.web.mvc.viewpage<ienumerable<mvcapplication1.models.news>>
So we can get to the corresponding data model.
In the view interface I am the following layout:
List<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>
<%}%>
In the news headlines I also added a link to get the ID of the news.
(8) This enables us to use the database instance in the MVC project.
Take a look at the effect chart:
After we click on the title: we will jump to:
The last parameter is the ID of the news. So we realize the display of database data.