好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

MVC3+Linqtosql显示数据库中数据表的数据

1:首先创建asp.net mvc3应用程序 2:创建项目完成后 找到controllers文件鼠标右击选择添加控制器 3 为models文件夹添加一个linq to sql类文件,然后把数据库中的数据库复制进来。如截图操作 4:添加控制器好后会生成一个HomeController.cs类文件,其代码如

1:首先创建asp.net mvc3应用程序

2:创建项目完成后 找到controllers文件鼠标右击选择添加控制器

3 为models文件夹添加一个linq to sql类文件,然后把数据库中的数据库复制进来。如截图操作

4:添加控制器好后会生成一个HomeController.cs类文件,其代码如下:

 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);
        }

    }
}  

View Code

5 为HomeController.cs类文件中的Index()添加视图,其操作如下所示:

6 添加视图完成后,其视图前台代码如下:

 @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  >  

View Code

7 最终测试运行结果

查看更多关于MVC3+Linqtosql显示数据库中数据表的数据的详细内容...

  阅读:56次