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

 

效果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM