zoukankan      html  css  js  c++  java
  • .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>

    效果如下:

  • 相关阅读:
    文件
    购物车
    session
    三级联动
    综合
    jquery弹窗插件
    Jquery
    PDO
    session cookie用法
    租房子
  • 原文地址:https://www.cnblogs.com/yuexiliuli/p/11622021.html
Copyright © 2011-2022 走看看