一、MVC模式

MVC(Model-View-Controller,模型—视图—控制器模式)用于表示一种软件架构模式。它
把软件系统分为三个基本部分:模型(Model),视图(View)和控制器(Controller)。

二、创建MVC项目

  这里使用的是VS 2017

  1.新建项目

  选择ASP.NET Web应用程序

  

 

  选择MVC

  

 

  项目创建后的大致内容如下:

  

 

   App_Data :这个目录跟一般的 ASP.NET website 是一样的,用于存放数据。

   Content :这个目录是建议用来存放一下资源文件的。例如 CSS、JS、图片等等。当然不愿 意的话,完全可以不放到这里来。

   Controllers :这个目录是建议将 Controller 类都放到这里来,方便管理。Controller 类的命名 必须以 Controller 结尾,例如一个名为 Home 的 Controller 则要命名为 HomeController。

  Models :这个目录是建议用来存放的业务实体、数据访问层代码的类的。当然,更好的做 法觉得应该是将 Models 独立为一个类库。

  Views :在默认情况下,所有的 view 文件都必须放到这个目录下来,每一个 Controller 对应 一个子目录,而且子目录的命名必须以 Controller 的命名一样。例如,HomeController 的 view 就应该放到 Home 子目录中。见到 Views 目录下还有一个 Shared 的子目录,这个子目录是 用于存放一些共享的 view 的,例如 Error.aspx 和 Site.Master 。 Controller 在 Views\ControllerNmae 中找不到指定的 view 的时候,会到 Shared 中去寻找。 

  下面来看一下 ASP.NET MVC 比较核心的 DLL:

    

 

  System.Web.Routing :URL 路由。将一个 URL 路由到对应的 Controller 上靠的就是这个。 是在 HttpModule 里面处理的。

  System.Web.Extensions :这个是 ASP.NET AJAX 的。 System.Web.Mvc: ASP.NET MVC 最主要的程序集。在 CodePlex 上放出源代码的就是这个 DLL。

  System.Web.Abstractions :这个程序集是一些相关的基类来的。例如 HttpContextBase、 HttpRequestBase 等等。

 

 

三、关于建立学生表的信息

  新建数据库并建表,字段如图所示。

  

 

 

  创建数据模式类

  在Models文件中右键选择“添加”——“类”,命名为:Student

  

 

 

输入如下代码:

 1     public class Student
 2     {
 3         [Key]
 4         [Required(ErrorMessage = "不能为空")]
 5         [Display(Name ="学号")]
 6         public string Sno { get; set; }
 7 
 8         [Required(ErrorMessage = "不能为空")]
 9         [Display(Name = "姓名")]
10         public string Sname { get; set; }
11 
12         [Required(ErrorMessage = "不能为空")]
13         [Display(Name = "性别")]
14         public string Sex { get; set; }
15 
16         [Required(ErrorMessage = "不能为空")]
17         [Display(Name = "QQ")]
18         public string SQQ { get; set; }
19 
20         [Required(ErrorMessage = "不能为空")]
21         [Display(Name = "宿舍")]
22         public string Sdormitory { get; set; }
23 
24     }
25 
26     public class studentDBContext : DbContext
27     {
28         [Key]
29         public DbSet<T_student> students { get; set; }
30     }

   在添加数据库上下文类时会遇到问题

 using System.Data.Entity;

  public class studentDBContext : DbContext
    {
        public DbSet<Student> students { get; set; }
    }

 这里可能会添加失败,这是由于没有添加EF(EntityFramework)的NuGet程序包

 这是添加的方法:

  工具——>NuGet包管理器——>程序包管理器控制台——>输入“Install-Package EntityFramework”

  或者在解决方案下的项目的引用中选择“NuGet程序包”,然后在浏览中输入“EntityFramework”并下载即可。

 

 连接数据库

点击"服务器资源管理器" ,右键数据连接 添加连接。然后选好服务器名,数据库名点 击"确定"按钮。然后查看属性,这里有连接字符串。

 

 打开项目Web.config文件

 

 

在这里添加连接字串

 

 

具体如下:

  <connectionStrings>
    <add name="studentDBContext" connectionString="Data Source=.;Initial Catalog=Student_data;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient"/>
  </connectionStrings>

 

编写 Controller  :在项目中找到"Controllers"文件夹右击,单击"添加" 再单击菜单"Controller…",按下图 填写: 
 

 

 

点击Index()添加视图

 

 

 视图类型使用模板

 

 视图代码:

 1 @model IEnumerable<MVC_test.Models.Student>
 2 
 3 @{
 4     ViewBag.Title = "Index";
 5 }
 6 
 7 <h2>Index</h2>
 8 
 9 <p>
10     @Html.ActionLink("Create New", "Create")
11 </p>
12 <table class="table">
13     <tr>
14         <th>
15             @Html.DisplayNameFor(model => model.Sname)
16         </th>
17         <th>
18             @Html.DisplayNameFor(model => model.Sex)
19         </th>
20         <th>
21             @Html.DisplayNameFor(model => model.SQQ)
22         </th>
23         <th>
24             @Html.DisplayNameFor(model => model.Sdormitory)
25         </th>
26         <th></th>
27     </tr>
28 
29 @foreach (var item in Model) {
30     <tr>
31         <td>
32             @Html.DisplayFor(modelItem => item.Sname)
33         </td>
34         <td>
35             @Html.DisplayFor(modelItem => item.Sex)
36         </td>
37         <td>
38             @Html.DisplayFor(modelItem => item.SQQ)
39         </td>
40         <td>
41             @Html.DisplayFor(modelItem => item.Sdormitory)
42         </td>
43         <td>
44             @Html.ActionLink("Edit", "Edit", new { id=item.Sno }) |
45             @Html.ActionLink("Details", "Details", new { id=item.Sno }) |
46             @Html.ActionLink("Delete", "Delete", new { id=item.Sno })
47         </td>
48     </tr>
49 }
50 
51 </table>

 

视图添加后运行

 

 

 添加创建,编辑,删除

代码如下:

 public class StudentController : Controller
    {
        //创建数据库连接对象
        private studentDBContext db = new studentDBContext();
        // GET: Student
        public ActionResult Index()
        {
            return View(db.students.ToList());
        }

        //创建
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(T_student s)
        {
            db.students.Add(s);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        
        //编辑
        public ActionResult Edit(string id)
        {
            T_student s = db.students.Find(id);//查找给定的实体
            if (s==null)
            {
                return HttpNotFound();
            }
            return View(s);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(T_student s)
        {
            if(ModelState.IsValid)
            {
                db.Entry(s).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(s);
        }
        //删除
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            T_student s = db.students.Find(id);
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ActionName("Delete")]       
        public ActionResult Deletel(string id)
        {
            T_student s = db.students.Find(id);

            db.students.Remove(s);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            T_student s = db.students.Find(id);
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }
    }  

并创建相应的视图

创建视图

 

 编辑视图

 

 

删除视图

 

 

明细视图:

 

 

 创建视图代码:

@model MVC_test.Models.Student

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Sno, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Sno, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Sno, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Sname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Sname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Sname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Sex, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.SQQ, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.SQQ, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SQQ, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Sdormitory, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Sdormitory, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Sdormitory, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

编辑视图代码:

@model MVC_test.Models.Student

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<div>
    <h4>Student</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Sname)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Sname)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Sex)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Sex)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.SQQ)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.SQQ)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Sdormitory)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Sdormitory)
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Sno }) |
    @Html.ActionLink("Back to List", "Index")
</p>

删除代码:

@model MVC_test.Models.Student

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Student</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Sname)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Sname)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Sex)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Sex)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.SQQ)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.SQQ)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Sdormitory)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Sdormitory)
        </dd>

    </dl>

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()

        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }
</div>

 

明细视图代码:

@model MVC_test.Models.Student

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Student</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Sname)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Sname)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Sex)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Sex)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.SQQ)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.SQQ)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Sdormitory)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Sdormitory)
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Sno }) |
    @Html.ActionLink("Back to List", "Index")
</p>

 

 

创建的视图均套用MVC中的模板,也可以自己手动编写(比较麻烦,容易出错)。

在StudentController.cs中编写代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using MVC_test.Models;
using System.Net;

namespace MVC_test.Controllers
{
    public class StudentController : Controller
    {   
        //创建数据库连接对象
        private studentDBContext db = new studentDBContext();
        // GET: Student
        public ActionResult Index()
        {
            return View(db.students.ToList());
        }
        //创建
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(Student s)
        {
            db.students.Add(s);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //编辑
        public ActionResult Edit(string id)
        {
            Student s = db.students.Find(id);//查找给定的实体
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Student s)
        {
            if (ModelState.IsValid)
            {
                db.Entry(s).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(s);
        }
        //删除
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student s = db.students.Find(id);
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ActionName("Delete")]
        public ActionResult Deletel(string id)
        {
            Student s = db.students.Find(id);

            db.students.Remove(s);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student s = db.students.Find(id);
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }
    }
}

运行项目

 

 

 

 

 

 

编辑操作(对可编辑的属性修改)

 

 

明细

 

 删除:

 

 

增删改查都一样正常。

 

 

     MVC模式工作流程

这是MVC的一个简单利用,也是初步入门学习的一个实例。主要是理解了工作流程,就能很好的理解MVC和对实例的学习。