MVC之查询demo

      上篇已经说过怎样建立MVC项目。这次主要讲述样例的实现。

其基本的功能就是从数据库中查询一些基本信息。

      前边我们已经将实体引入到了项目中,这时Model目录中已经出现了我们建立的newsSystem.edmx文件。当中会包括着我们的实体类中全部的信息,以及关系图:

 

      

      首先须要在controller目录中建立一个控制器,右键--加入--控制器,这时要注意。控制器的命名必须以Controller结尾

 

      

      建好控制器之后须要加入视图,视图也就是显示数据和输入数据的界面(相当于三层中的U层),直接在控制器中的ActionResult中,右键--加入视图:

 

      

      功能实现的基本模块都已经建立好,以下就開始代码的书写了:

      控制器中的代码例如以下:

using System;
usingSystem.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
usingMVCNewSystem.Models;
namespaceMVCNewSystem.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        //实例化实体model
        newsSystemEntities db = newnewsSystemEntities();
        public ActionResult Index()
        {
            //使用Linq语句。查询新闻
            List<news> list = (from d indb.news  select d).ToList();
            //将集合传给视图
           ViewData["DataList"]=list;
            //载入视图
            return View();
        }
 
    }
}
 


      视图中的代码例如以下: 

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport"content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        #newsList{
            border:1px solid #0094ff;
            1000px;
            margin:10px auto;
            border-collapse:collapse;
        }
            #newsList th.a, td.a {
                 100px;
                padding: 10px;
                border: 1px solid #0094ff;
            }
            #newsList th.b, td.b {
                 150px;
                padding: 10px;
                border: 1px solid #0094ff;
            }
            #newsList th.c, td.c {
                 400px;
                padding: 10px;
                border: 1px solid #0094ff;
            }
    </style>
</head>
<body>
    <table id="newsList">
        <tr>
            <thclass="a">id</th>
            <th class="a">标题</th>
            <th class="c">内容</th>
            <th class="b">创建时间</th>
            <th class="a">类别ID</th>
            <th class="a">操作</th>
        </tr>
     @foreach (MVCNewSystem.Models.news n inViewData["DataList"] as List<MVCNewSystem.Models.news>)
     {
          <tr>
              <tdclass="a">@n.id</td>
              <tdclass="a">@n.title</td>
              <tdclass="c">@n.content</td>
              <tdclass="b">@n.createTime</td>
              <tdclass="a">@n.caID</td>
              <td class="b">
                  <a href="">删除</a>
                  <a href="">改动</a>
              </td>
        </tr>
     }
    </table>
   
</body>
</html>


      其效果例如以下:

      这样我们的一个小小的MVC样例就做完了。尽管这仅仅是一个简单的demo,可是对我初次理解MVC确有非常大的帮助。知道了这个实现的过程。为自己深入的学习MVC奠定了一个非常好的基础。


原文地址:https://www.cnblogs.com/mfmdaoyou/p/6852306.html