MVC 实现数据库的数据加载到view视图

最近刚接触到MVC的学习,下面通过一个小小的demo来实现ef数据怎么在View视图上显示
下面是demo的运用图
在这里插入图片描述
现在就具体代码实现:
1)因为要用到数据库里的数据,所以我们首先要实现在model层实现 ef数据模型,然后在重写一个类(这个类用于实现查询方法)

  public class UserSever
    {
        public static List<Sysuser> Chaxunq() {//<Sysuser>是表名

            using (fashionshoppingDBEntities db=new fashionshoppingDBEntities())
            {
                return db.Sysuser.ToList();
            }
        }
    }

2)ef模型和查询方法生成后,index action 相关的前后台的代码如下

2.1)Index action 所对应的view视图的代码

 <div> 
        <table>
            <tr>
                <th>编号</th>
                <th>登录名</th>
                <th>操作</th>
            </tr>
              @foreach ( var item in ViewBag.shuju)
                 
              {
                  <tr>
                      <td>@item.id</td>
                      <td>@item.username</td>//item.username是表的名字
                      <td><a href="/First/About?id= @item.id">详情</a></td>
                    

                  </tr>
              }



        </table>


    </div>

2.2))Index action 的后台代码

  public ActionResult Index()
        {
            ViewBag.shuju = UserSever.Chaxunq();//从数据库里查询的数据保存到ViewBag中返回给视图
            return View();
        }

3 About action 相关的前后台的代码如下
3.1)About action代码

   public ActionResult About() {
     fashionshoppingDBEntities db = new fashionshoppingDBEntities();//上下文对象
            string id = Request["id"];//**请求index 页面中 <td><a href="/First/About?id= @item.id">详情</a>** 的值
            ViewBag.ses = db.Sysuser.Find(Convert.ToInt32(id)); //不知道为什么不能掉UserSever.Chaxunq()这个方法,会报错
          
            return View();
        
        }

3.2)About 所对应的前端代码

   <div> 
        <h3>@ViewBag.ses.id</h3>//.后面的是表的列名
        <h3>@ViewBag.ses.username</h3>

    </div>
posted @ 2020-05-22 17:16  南墙1  阅读(440)  评论(0编辑  收藏  举报