MVC之查询demo

mac2022-06-30  84

      上篇已经说过如何建立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; width:1000px; margin:10px auto; border-collapse:collapse; } #newsList th.a, td.a { width: 100px; padding: 10px; border: 1px solid #0094ff; } #newsList th.b, td.b { width: 150px; padding: 10px; border: 1px solid #0094ff; } #newsList th.c, td.c { width: 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/victor-grace/p/7253788.html

最新回复(0)