1:首先创建asp.net mvc3应用程序
2:创建项目完成后 找到controllers文件鼠标右击选择添加控制器
3 为models文件夹添加一个linq to sql类文件,然后把数据库中的数据库复制进来。如截图操作
4:添加控制器好后会生成一个HomeController.cs类文件,其代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcTestData.Models; namespace MvcTestData.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { TestDataContext txtData = new TestDataContext(); var result=from info in txtData.StuTable select info; ViewData["data"] = result; return View(result); } } }
5 为HomeController.cs类文件中的Index()添加视图,其操作如下所示:
6 添加视图完成后,其视图前台代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@using MvcTestData.Models <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body> <div> <table border="0" cellspacing="0" cellpadding="0" width="100%" style="text-align:center" > <tr> <th>序号</th><th>学号</th><th>姓名</th><th>性别</th><th>年龄</th><th>住址</th> </tr> @foreach (StuTable info in (ViewData["data"] as IEnumerable<StuTable>)) { <tr> <td>@info.ID</td> <td>@info.StuId </td> <td>@info.StuName </td> <td>@info.StuSex </td> <td>@info.StuAge </td> <td>@info.StuAddress </td> </tr> } </table> </div> </body> </html>
7 最终测试运行结果