欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

使用Visual Studio新建一个控制器和视图,在控制器里获取数据库表的数据 有大用

使用工具 :Visual Studio 2015   ,  SQL server

                                     

 

1.在使用 Visual Studio 之前,我先带着大家了解如何使用 Visual Studio 来创建一个视图。

(1)当我们打开 Visual Studio 2015后 ,在首页点击新建项目

 

(2)这时会有个弹窗,我们选择Empty,勾选MVC 后点击确定

 

(3)点击确定后进行首页 ,我们在右边找到 ”解决方案资源管理器“ ,如果没有就在单击视图,点击解决方案资源管理器

 

(4)点击解决方案资源管理器后,我们在Controllers里添加一个控制器 

注 :Controllers文件夹是用来放置控制器的文件夹

 

(5)选择 ” MVC S 控制器 - 空 “   ,点击添加 

修改名称

 

(6)选中 Index() ,点击鼠标右键添加视图

使用布局页不用的打✓,点击添加,一个视图就添加成功了。

成功添加视图后,我们就来进行下一步了。

 

2.在 Visual Studio 里获取SQL里面的数据 。

      

   打开 Visual Studio 2015 后找到  Models(Modees :数据库里面的表会映射到这给文件夹里面来。)

 

(1)Models ———》添加 ———》 新建项

 

(2)点击 数据 ———》ADO.NET实体数据模型

 

(3)点击 来自数据库的 EF 设计器——》确定

 

(4)点击新建连接 ——》填写服务器名称 ——》登录———》 选择数据库名称——》确定

(5)获取成功

         

 

3.在视图里建一个表格,放置数据

(1)添加一个实例化,实体模型

  1. public class LinqSelectController : Controller
  2. {
  3. // GET: LinqSelect
  4. //实例化 实体模型
  5. Models.TestDBEntities myModel = new Models.TestDBEntities();
  6. public ActionResult Index()
  7. {
  8. return View();
  9. }

实例化 在面向对象的编程中,通常把用类创建对象的过程称为实例化。

               类名 对象名 = new 类名(参数1,参数2...参数n);

              如 Date date=new Date();就是用日期类创建了一个日期的对象,就叫对象的实例化。

              多数语言中,实例化一个对象 就是为对象开辟内存空间,或者是不用声明,直接使用

              new 构造函数名(),建立一个临时对象。

   

(2)查询表格数据

  1. /// <summary>
  2. /// 查询表格数据
  3. /// </summary>
  4. /// <returns></returns>
  5. public ActionResult SelectStudent()
  6. {
  7. var student = from tbStudent in myModel.SYS_Student
  8. select tbStudent;
  9. return Json(student, JsonRequestBehavior.AllowGet);
  10. }

(3)在index视图里搭建一个表格样式

    HTML部分

  1. <div class="container">
  2. <table id="tbStudent" class="table table-bordered mt-5">
  3. <thead>
  4. <tr>
  5. <th>序号</th>
  6. <th>姓名</th>
  7. <th>性别</th>
  8. <th>身份证号码</th>
  9. <th>电话号码</th>
  10. <th>地址</th>
  11. </tr>
  12. </thead>
  13. <tbody>
  14. </tbody>
  15. </table>
  16. </div>

    JS部分

  1. $(document).ready(function () {
  2. $.get("/LinqSelect/SelectStudent", function (jsonData) {
  3. console.log(jsonData);
  4. var str = "";
  5. for (var i = 0; i < jsonData.length; i++) {
  6. str += '<tr><td>'  + (i + 1) +
  7. '</td><td>' + jsonData[i].StudentName +
  8. '</td><td>' + jsonData[i].StudentSex +
  9. '</td><td>' + jsonData[i].StudentIDNum +
  10. '</td><td>' + jsonData[i].StudentTelphome +
  11. '</td><td>' + jsonData[i].StudentAddress + '</td></tr>';
  12. console.log(jsonData[i])
  13. $("#tbStudent tbody").append(str);
  14. }
  15. })
  16. })

注 :布局使用了Bootstrap框架。

结果:

 


来自  https://blog.csdn.net/HG13542386794/article/details/117434993


普通分类: