2016-AspNet-MVC教学-2-数据来源及超链接测试

来源:互联网 发布:长沙淘宝哪家卤味好吃 编辑:程序博客网 时间:2024/05/17 15:19

第一步:单独启动数据Sql Server,创建数据库DBTest,并在此数据库中创建表格Register:


第二步:启动MVC开发平台,在平台Server Explore 增加Sql数据连接:


第三步:新建VC# MVC4 Project,Basic类型:

第四步:在Models目录下,添加Student类:

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace MvcDataTest.Models{    public class Student    {        public int ID;        public string Name;        public int Age;        public string ClassName = "2015-ECommerce-1";    }}

继续往Models目录下 New Item->数据(Data)->ADO.NET实体数据模型->命名为:DBTestModel ,后面步骤命名为 DBTestEntities 等名称


Models目录下面出现:



第五步:Controllers目录下面,添加HomeController.cs文件,里面代码修改如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using MvcDataTest.Models;namespace MvcDataTest.Controllers{    public class HomeController : Controller    {        //        // GET: /Home/        public ActionResult Index()        {            DBTestEntities db = new DBTestEntities();            var v = db.Register;            return View(v);        }        public ActionResult Second()        {            Student stu1 = new Student();            stu1.ID = 1;            stu1.Name = "zhangsan";            stu1.Age = 20;            return View(stu1);        }    }}
第六步:编译工程,然后,为上述的Index()的Action添加相应的View,Index.cshtml代码产生时,应该采用强类型(Register),最终修改为如下:
@model IEnumerable<MvcDataTest.Models.Register>@{    ViewBag.Title = "Index";}<h2>Index</h2><table>    <tr>        <th>            @Html.DisplayNameFor(model => model.Name)        </th>        <th>            @Html.DisplayNameFor(model => model.Sex)        </th>        <th>            @Html.DisplayNameFor(model => model.Age)        </th>            </tr>@foreach (var item in Model) {    <tr>        <td>            @Html.DisplayFor(modelItem => item.Name)        </td>        <td>            @Html.DisplayFor(modelItem => item.Sex)        </td>        <td>            @Html.DisplayFor(modelItem => item.Age)        </td>            </tr>    }</table><p>       @Html.ActionLink("Link To Second", "Second")</p>

同理,为Second()的Action添加相应的View,Second.cshtml代码产生时,应该采用强类型(Student),最终修改为如下:

@model MvcDataTest.Models.Student@{    ViewBag.Title = "Second";}<h2>Second</h2><fieldset>    <legend>Student</legend>     @Model.ID      <hr  />     @Model.Name      <hr />     @Model.Age      <hr />     @Model.ClassName</fieldset><p>       @Html.ActionLink("Back to Index", "Index")</p>
注意:Index.cshtml里面有个指向Second的链接,Second.cshtml里面有个指向Index的链接.


最终测试界面如下:


小结:通过此例,理解动态数据的来源,一个来自Sql数据库,一个来自Action中的自己产生的数据. 同时,理解类的作用:用类可以创建实例,实例里面可以装数据.此实例可以传递到view,View可以采用强类型,来匹配传输到本View 的数据.同时,掌握超链接的Html助记符的使用.

0 0
原创粉丝点击