MVC5 Demo (1), mvc5demo

Source: Internet
Author: User

MVC5 Demo (1), mvc5demo
Brief Introduction

I decided to post a blog after I had nothing to worry about recently. As there have been no new projects recently, I read some related information about MVC 5. I have been working for more than two years and feel like I am still a chicken. This article aims to learn and communicate with each other.

It took several days to create an MVC 5 Demo, including user logon, user management, and a query page. The Demo mainly uses the MVC5 and EF6 frameworks.

I. logon page

1. First, create a UserInfoModel with the following code:

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 contains some basic information about the user and performs non-empty verification on the model and email format verification. (Model verification can refer to: http://www.studyofnet.com/news/339.html)

 

2. Reference EF6 dll (enter install-package entityframework in Tools> NuGetPackageManager> PackageManagerConsole), create a folder named DAL, and add UserContext. cs. The Code is as follows:

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>();        }    }}

 

The constructor is used to initialize the connection string (the parameter "UserContext" is web. the connectionString key in the config file, web. the configuration of the confg file will be discussed later) The OnModelCreating method is used to prevent the problem that EF creates tables in lower case based on the Model.

 

3. Add UserInitializer. cs to the DAL file. The Code is as follows:

 

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();        }    }}

The method of rewriting Seed () is to initialize data when the database does not exist or the model changes. The method of reloading InitializeDatabase () is to solve the bug when EF deletes the table and recreates the table during model changes. (The table is in use and cannot be deleted ).

In web. config, add a database connection string (the database uses the lightweight database LocalDB that comes with)

<ConnectionStrings>

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

</ConnectionStrings>

Add the tag and initialize the context (the UserInitializer method is executed by default)

<EntityFramework>

<Contexts>

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

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

</Context>

</Contexts>

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

<Parameters>

<Parameter value = "v11.0"/>

</Parameters>

</Defaultonfactory>

<Providers>

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

</Providers>

</EntityFramework>

 

4. Add LoginController to the controller. The Code is as follows:

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");        }    }}

 

Add the corresponding View LoginIn. cshtml. The Code is as follows:

@ {ViewBag. Title = "Login"; Layout = "~ /Views/Shared/_ LoginLayout. cshtml ";}@ model MVCLogin. models. userInfoModel @ * @ if (Request. isAuthenticated) {@ Html. label ("logged-on user")} else {@ Html. label ("logged-on user")} * @ <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 ,. for M-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> </div> @ Ht Ml. 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 class = "control-group"> @ Html. labelFo R (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 class = "control-group"> <div class = "controls"> <input type = "submit" value = "Log in" class = "btn-primary"/> </div >}</div> @ section Scripts {@ Scrip Ts. Render ("~ /Bundles/jqueryval ")}

 

The page is as follows:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.