你的位置:首页 > ASP.net教程

[ASP.net教程]MVC5 Demo (一)


   简述

      最近闲来无事,决定发篇博客。由于最近一直没有新的项目,所以看了些关于MVC 5的相关资料。工作两年多,感觉自己仍是菜鸡一枚,此篇文章是为了一起学习交流。

  花了几天时间做了个MVC 5 的Demo,包括用户登录、用户管理以及一个查询页面。该Demo主要用的是MVC5和EF6框架。

一、登录页面

      1.首先,我们创建一个UserInfoModel,代码如下:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Web;namespace MVCLogin.Models{  public class UserInfoModel  {    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]    [Display(Name = "Employee Number")]    public int EmployeeID { get; set; }    [Required]    [RegularExpression(@"[A-Za-z0-9.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email address format is not correct. ")]    [Display(Name = "Email Address")]    public string UserName { get; set; }    [Required]    [DataType(DataType.Password)]    [Display(Name = "Password")]    public string Password { get; set; }    [Display(Name = "NTAccount")]    public string NTAccount { get; set; }    [Display(Name="Admin Role")]    public bool Admin { get; set; }  }}

 

 UserInfoModel包含了用户的一些基本信息, 并且对model做了非空验证以及邮箱格式验证。(Model 验证具体可参考:  http://www.studyofnet.com/news/339.html)

 

  2.引用 EF6 dll(在Tools>NuGetPackageManager>PackageManagerConsole里输入install-package entityframework即可),然后创建一个名为DAL的文件夹,添加UserContext.cs,代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data.Entity;using System.Data.Entity.ModelConfiguration.Conventions;using MVCLogin.Models;namespace MVCLogin.DAL{  public class UserContext : DbContext  {    public UserContext()      : base("UserContext")    {    }    public DbSet<UserInfoModel> UserInfo { get; set; }    public DbSet<Student> Student { get; set; }    protected override void OnModelCreating(DbModelBuilder modelBuilder)    {      modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();    }  }}

 

 构造函数用于初始化连接字符串(参数"UserContext"为 web.config文件中 connectionString的key,web.confg文件的配置在后面会讲到)重写OnModelCreating方法是为了防止EF根据Model创建表时大小写的问题。

 

 3.在DAL文件中再添加UserInitializer.cs,代码如下:

 

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data.Entity;using MVCLogin.Models;namespace MVCLogin.DAL{  public class UserInitializer : DropCreateDatabaseIfModelChanges<UserContext>  {    public override void InitializeDatabase(UserContext context)    {      context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction      , string.Format("ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", context.Database.Connection.Database));      base.InitializeDatabase(context);    }    protected override void Seed(UserContext context)    {      var User = new List<UserInfoModel>      {        new UserInfoModel{ NTAccount="ASIAPACIFIC", UserName="zhu.cao@hpe.com", Password="111",Admin=true },        new UserInfoModel{ NTAccount="AMERICA", UserName="Barry@hpe.com" ,Password="111",Admin=false },        new UserInfoModel{ NTAccount="EMEA", UserName="Candy@hpe.com",Password="111" ,Admin=true }      };      User.ForEach(u => context.UserInfo.Add(u));      context.SaveChanges();      var Student = new List<Student>      {        new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01"), Grade=Grade.A},        new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01"), Grade=Grade.B},        new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01"), Grade=Grade.C},        new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01"), Grade=Grade.A},        new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01"), Grade=Grade.D},        new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01"), Grade=Grade.F},        new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01"), Grade=Grade.C},        new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01"), Grade=Grade.B}      };      Student.ForEach(s => context.Student.Add(s));      context.SaveChanges();    }  }}

重写Seed()方法是在数据库不存在或者model改变时初始化数据,重载InitializeDatabase()方法是为了解决model更改时EF删除表重新创建时的bug。(table被占用,无法删除)。

  在web.config中,添加数据库连接字符串 (数据库采用的是vs自带的轻量级数据库LocalDB)

<connectionStrings>

<add name="UserContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=UserInfo;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

</connectionStrings>

添加标记的部分,初始化context(默认执行UserInitializer方法)

<entityFramework>

    <contexts>

      <context type="MVCLogin.DAL.UserContext, MVCLogin">

        <databaseInitializer type="MVCLogin.DAL.UserInitializer, MVCLogin" />

      </context>

    </contexts>

    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">

      <parameters>

        <parameter value="v11.0" />

      </parameters>

    </defaultConnectionFactory>

    <providers>

      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />

    </providers>

  </entityFramework>

 

 4.在controller添加LoginController,代码如下:

   

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Web;using System.Web.Mvc;using MVCLogin.Models;using System.Web.Security;using System.Security.Principal;using MVCLogin.DAL;namespace MVCLogin.Controllers{  public class LoginController : Controller  {    //    // GET: /Login/    private UserContext UC = new UserContext();    public ActionResult LoginIn(string returnUrl)    {      ViewBag.returnUrl = returnUrl;      return View();    }    [HttpPost]    [ValidateAntiForgeryToken]    public ActionResult LoginIn(UserInfoModel User, string returnUrl)    {      if (ModelState.IsValid)      {        try        {          var Account = UC.UserInfo.Where(u => u.UserName == User.UserName.Trim());          if (Account.Count()>0)          {            FormsAuthentication.SetAuthCookie(User.UserName, false);            return RedirectToAction("Index", "Home");          }          else          {            ModelState.AddModelError("", "Invalid username or password.");          }        }        catch (Exception err)        {          throw new Exception(err.Message);        }      }      return View(User);    }    public ActionResult LoginOut()    {      FormsAuthentication.SignOut();      return RedirectToAction("LoginIn");    }  }}

 

添加对应的View LoginIn.cshtml,代码如下:

@{  ViewBag.Title = "Login";  Layout = "~/Views/Shared/_LoginLayout.cshtml";}@model MVCLogin.Models.UserInfoModel@*@if(Request.IsAuthenticated)  {    @Html.Label("已登录用户")  }  else  {    @Html.Label("未登录用户")  }*@<style type="text/css">  .form-horizontal .control-group .control-label {    width: 150px;    /*    padding-left: 5px;*/  }  .form-horizontal .control-group {    padding-right: 20px;    padding-top: 10px;  }    .form-horizontal .control-group .controls input, .form-horizontal .control-group .controls button {      width: 100%;    }</style><div class="container" style="padding-left:170px">  @using (Html.BeginForm("LoginIn", "Login", new { returnUrl = ViewBag.returnUrl }, FormMethod.Post, new { @class = "form-signin form-horizontal", role = "form", style = "width:500px;height:550px;max-width:500px" }))  {    <div style="padding-top:60px">      <fieldset></fieldset>    </div>    @Html.AntiForgeryToken()    @Html.ValidationSummary(true)    <div class="control-group" style="margin-top: 20px;">      @Html.LabelFor(m => m.UserName, new { @class = "control-label" })      <div class="controls">        @Html.TextBoxFor(m => m.UserName, new { @placeholder = "Email Address" })        @Html.ValidationMessageFor(m => m.UserName, null, new {@style="color:red"})      </div>    </div>  <div class="control-group">    @Html.LabelFor(m => m.Password, new { @class = "control-label" })    <div class="controls">      @Html.PasswordFor(m => m.Password, new { @placeholder = "Password" })      @Html.ValidationMessageFor(m => m.Password, null, new { @style = "color:red" })    </div>  </div>  <div class="control-group">    <div class="controls">      <input type="submit" value="Log in" class="btn btn-primary" />    </div>  </div>  }</div>@section Scripts {  @Scripts.Render("~/bundles/jqueryval")}

 

页面如下:

 

登录页面的功能基本已经完成了,下篇将讲解用户管理页面。

 

 

参考资料:
http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application