【MVC】.Net实践(二)—数据的显示

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cxh6863/article/details/83471932

关系图

要想对数据进行操作,就先要对结构和操作有所了解,Controller中的方法与View中的cshtml相对应
结构如图所示
在这里插入图片描述

显示数据库中的数据

(1)在HomeController的Index中用Viewdata或ViewBag绑定数据

public ActionResult Index()
{
         List<Models.BlogUser> list = (from d in db.BlogUser where d.State == false select d).ToList();
         //ViewBag.DataList = list;
         ViewData["DataList"] = list;
         return View();
 }

(2)新建视图,即新建了一个Index.cshtml文件

在这里插入图片描述

(3)在Index.cshtml编写代码显示数据

第一种:这是最简单的方法

@Html.Raw(ViewBag.HtmlStr)

第二种:可以用table来显示,这样可以美观一些

在最上方需要引用空间:@using MVC练习.Models

<table id="tbList">
        <tr>
            <th>id</th>
            <th>姓名</th>
            <th>状态</th>
            
        </tr>

        @Html.Raw(ViewBag.HtmlStr)
        @foreach (BlogUser a in ViewData["DataList"] as List<BlogUser>)
        {
            <tr>
                <td>@a.Id</td>
                <td>@a.Name</td>
                <td>@a.State</td>
               
            </tr>
            
        }
           
    </table>

布局代码

<style type="text/css">
        #tbList {
            border: 1px solid #0094ff;
            width: 800px;
            margin: 10px auto;
            border-collapse: collapse;
        }
            #tbList th, td {
                border: 1px solid #0094ff;
                padding: 10px;
            }
 </style>

结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/cxh6863/article/details/83471932
今日推荐