当前位置:Gxlcms > 数据库问题 > .net mvc(一)将数据库提取出来显示在网页

.net mvc(一)将数据库提取出来显示在网页

时间:2021-07-01 10:21:17 帮助过:36人阅读

MusicStoreBD();

## 二、添加操作
①提取数据
②显示数据
```csharp
public ActionResult Index()
{
var musiclist = from i in ms.MusicInfo select i;
//LinQ语句,从数据库中提取数据
//MusicInfo是一张表
return View(musiclist.ToList());
//执行ToList()操作,列表
}
```
注:MusicStore控制器的完整代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MusicStore.Models;
namespace MusicStore.Controllers
{
public class StoreController : Controller
{
// GET: Store
MusicStoreBD ms = new MusicStoreBD();
public ActionResult Index()
{
var musiclist = from i in ms.MusicInfo select i;
//LinQ语句,从数据库中提取数据
//MusicInfo是一张表
return View(musiclist.ToList());
//执行ToList()操作,列表
}
}
}

 

三、添加视图
①右键单击:Index(),选择“添加视图”选项
技术图片
这是添加视图后自动倒转到的Index视图
下面我们为页面添加数据。
四、显示数据库里面的数据
我们刚才使用ToList()方法,把musiclist强制转换成立列表,下载我们就要用mysiclist来显示数据。
①使用强类型视图,把表转换可枚举的,也就是把数据一个个显示出来。

@model IEnumerable<MusicStore.Models.MusicInfo>

②把数据显示出来
我们在这里使用foreach循环。
举例:把MusicStore的MusicID,即编号显示出来
代码:

技术图片

怎么看效果?右键单击:在浏览器中查看 或者 CTRL+shift+W
效果如下:

技术图片

③完整提取出数据:

@model IEnumerable<MusicStore.Models.MusicInfo>
@{
    ViewBag.Title = "Index";
}

<h1>我的音乐情况</h1><br /><br/>

<table class="table">
    <tr>
        <th>编号</th>
        <th>名称</th>
        <th>时间</th>
        <th>价格</th>
        <th>评级</th>
    </tr>
    <tbody id="userlist">
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.MusicID
                </td>
                <td>
                    @item.MusicName
                </td>
                <td>
                    @item.MusicCreateTime
                </td>
                <td>
                    @item.MusicPrice
                </td>
                <td>
                    @item.MusicLevel
                </td>
            </tr>
        }
    </tbody>
</table>

 

效果如下:
技术图片

.net mvc(一)将数据库提取出来显示在网页

标签:``   连接数据库   eve   项目   cti   clist   编号   ace   shift   

人气教程排行