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

默认已经连接数据库,数据库实体名称是:MusicStoreBD.cs

一、实例化数据库

①在项目文件夹下的Controller中创建新控制器MusicStore(可选操作)
②实例化:MusicStoreBD ms = new MusicStoreBD();

MusicStoreBD ms = new MusicStoreBD();

二、添加操作

①提取数据
②显示数据

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>

效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值