MVC3+Linq to sql 显示数据库中数据表的数据

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 最终测试运行结果

 

转载于:https://www.cnblogs.com/thbbsky/p/3144142.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值