Simple login and MVC4 application development in ASP. NET mvc4 Web Application Development

Source: Internet
Author: User

Simple login and MVC4 application development in ASP. NET mvc4 Web Application Development

1. Create an ASP. net mvc Web Application

Create a project --> template --> Visual C # --> Web-> select ASP. NET Web application

Select MVC. The default view engine is Razor. If you do not select this option to create a unit test project, change the authentication (no authentication)

In this way, a basic ASP. net mvc Web application is created ~~

2. Create a T4 template and establish a connection with the SQL Sever database (two forms are available: method 1 is used later)

Right-click [Models] --> Add --> Create item --> select data --> ADO. NET Object Data Model

There are two options: 1. Generate based on the existing SQL Server database. 2. Create a database model and then generate the required database based on the model.

1. Select generate from database

Next step

Create connection --> server name. (. Indicates host) --> select or enter database name Ddup

DdupEntities is the object class name of the created EF context container

Next (select the database table to be added to the Model)

Click Finish. The T4 template generates the corresponding entity model based on the database.

2. Select an empty model (EF Code First)

 

Right-click the blank space and choose add> entity

The object name T001Admin corresponds to the generated database table name T001Admin;The default object set is T001AdminSet, Which is changed to be consistent with the object name;The key attribute is the primary key of the object (Code First sets this primary key Id to auto-increment by default in the database)

In this way, we have created a table T001Admin with an auto-incrementing primary key Id.

Create other attributes of the T001Admin object.

Right-click Properties> Add> scalar property, and change its name to Account.

Right-click [Account] --> Properties and set the attributes of the Account

Similarly, the T001Admin table and T002AdminGroup table are created.

 

Create a primary foreign key Association: choose View> toolbox on the menu bar and click associate]

Click [Id] of the T001Admin table --> and then click fk_T001Admin of the T002AdminGroup table, so that the primary and foreign key associations are established.

Then, right-click the editing area --> Generate a database based on the model (before that, you must create a new database: Ddup in SQL Server)

Create connection --> server name. (. indicates the host) --> select or enter the Database Name (select the database Ddup that has been previously created)

OK --> next. Here, the T4 template converts the created model into an SQL statement and stores it in the Model1.edmx. SQL file of Models.

 

Click Finish to generate the corresponding SQL file.

 Click in the upper left corner. The Server name is.

Click Connect. The message shows that the command has been successfully completed. In the Ddup database, the database table corresponding to the object model we created previously has been successfully generated.

Note: model1iner iner here is the name of the EF context container created later.

We can rename this Web. config and change name = "Model1Container" to name = "DBEntities"

  <connectionStrings>    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Ddup-20160724074025;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Ddup-20160724074025.mdf" />    <add name="Model1Container" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Ddup;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />  </connectionStrings>

In Model1.Context. cs, change all Model1Container to DBEntities.

Before modification:

    public partial class Model1Container : DbContext    {        public Model1Container()            : base("name=Model1Container")        {        }            protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            throw new UnintentionalCodeFirstException();        }            public DbSet<T001Admin> T001Admin { get; set; }        public DbSet<T002AdminGroup> T002AdminGroup { get; set; }    }

After modification:

public partial class DBEntities : DbContext    {        public DBEntities()            : base("name=DBEntities")        {        }            protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            throw new UnintentionalCodeFirstException();        }            public DbSet<T001Admin> T001Admin { get; set; }        public DbSet<T002AdminGroup> T002AdminGroup { get; set; }    }

3. Create the first Model-M001LoginDemo. cs

Right-click [Models] --> Add --> class (M001LoginDemo. cs)

DdupEntities is the object connection name in web. config that was previously configured.

 

Using Ddup. models. viewModel; using System. collections. generic; using System. linq; using System. web; namespace Ddup. models {/// <summary> /// logon model demonstration // </summary> public class M001LoginDemo {# region 1.0) /// <summary> /// 1. Define a Boolean-type method. // 2. In the future, the Controller receives true or false values to determine whether logon is allowed/ /// </summary> /// <param name = "username"> </param> /// <param name = "pwd"> </param> // <returns> true or false </returns> public static Boolean LoginDemo1 (string account, string pwd) {// initialize the EF context container DdupEntities db = new DdupEntities (); // m => m. account this is a lambda expression // db. t001Admin. firstOrDefault (m => m. account = account & m. password = pwd); The return type is T001Admin. Therefore, a strong T001Admin type is defined to receive data. // T001Admin model = db. t001Admin. firstOrDefault (m => m. account = account & m. password = pwd); // var can intelligently identify the desired strong type and convert it to var model = db. t001Admin. firstOrDefault (m => m. account = account & m. password = pwd); if (model = null) {return false;} else {return true ;}} # endregion # region Method 2: // <summary> // 1. Define a method of the T001Admin type. // 2. whether to receive or not in the Controller in the future is null to determine whether logon is allowed // </summary> /// <param name = "account"> </param> /// <param name = "pwd"> </param> /// <returns> </returns> public static T001Admin LoginDemo2 (string account, string pwd) {// initialize the EF context container DdupEntities db = new DdupEntities (); return db. t001Admin. firstOrDefault (m => m. account = account & m. password = pwd);} # endregion # region logon method 3 (recommended) /// <summary> /// 1. Define a T001Admin method. // 2. Determine whether to allow logon if null is received in the Controller in the future/ // 3. model used here (Vm001 logon view Model) as the parameter type, you need to add a new folder ViewModel under Models, and then create the Vm001 logon view model under ViewModel. cs, // finally, you need to import the namespace and add using Ddup at the beginning. models. viewModel; /// </summary> /// <param name = "account"> </param> /// <param name = "pwd"> </param> /// <returns> </returns> public static T001Admin LoginDemo3 (Vm001 logon view model) {// initialize the EF context container DdupEntities db = new DdupEntities (); return db. t001Admin. firstOrDefault (m => m. account = model. account & m. password = model. pwd) ;}# endregion }}
Using System; using System. collections. generic; using System. linq; using System. web; namespace Ddup. models. viewModel {public class Vm001 logon view model {public string account {get; set;} public string pwd {get; set;} public string Vcode {get; set ;}}}

 

4. Create a Controller -- C01LoginController. cs (Here we choose -- MVC 5 Controller-null)

Right-click Controllers and choose add controller.

Using Ddup. models; using Ddup. models. viewModel; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; namespace Ddup. controllers {public class C01LoginController: Controller {public ActionResult Login () {return View ();} [HttpPost] public ActionResult Login (Vm001 logon View model) {try {if (ModelState. isValid) {# region 1.0: logon demonstration method 1 // var userinfo1 = M001LoginDemo. loginDemo1 (model. account, model. pwd); // if (userinfo1 = true) // {// RedirectToAction ("Index", "Home"); //} # endregion # region 2.0: logon demonstration method 2 // var userinfo2 = M001LoginDemo. loginDemo2 (model. account, model. pwd); // if (userinfo2 = null) // {// RedirectToAction ("Index", "Home"); //} # endregion # region 3.0: logon demonstration method 3 var userinfo3 = M001LoginDemo. loginDemo3 (model); if (userinfo3 = null) {RedirectToAction ("Index", "Home") ;}# endregion }} catch (Exception ex) {ModelState. addModelError ("", ex. message) ;}return View ("Error ");}}}

5. Create a logon view Login. cshtml

Right-click Login and choose create logon view.

@ Model Ddup. models. viewModel. vm001 logon view Model @ {ViewBag. title = "Login" ;}@ using (Html. beginForm () {@ Html. validationSummary (true) <div class = "form-group"> class = "row"> @ Html. labelFor (m => m. account, new {@ class = "col-md-5 control-label", @ style = "text-align: right", @ for = "account "}) <div class = "col-md-7"> @ Html. textBoxFor (m => m. account, new {@ class = "form-control", placeholder = "Enter the user name", @ style = "width: 240px;", id = "account "}) @ Html. validationMessageFor (m => m. account) </div> <div class = "form-group" style = "height: 40px; "> <div class =" row "> @ Html. labelFor (m => m. pwd, new {@ class = "col-md-5 control-label", @ style = "text-align: right", @ for = "pwd "}) <div class = "col-md-7"> @ Html. passwordFor (m => m. pwd, new {@ class = "form-control", placeholder = "enter the password", @ style = "width: 240px;", id = "pwd "}) @ Html. validationMessageFor (m => m. pwd) </div> <div class = "form-group"> <div class = "col-md-5"> </div> <div class = "col-md-2 col-xs-4> <input type = "submit" value = "login" class = "btn-default"/> </div> <div class = "col-md-5 col-xs-8"> <input type = "reset" value = "reset" class = "btn-default"/> </div>}

Note: No verification code is used.

 

I am a beginner. If you have any questions, please forgive me. I hope you can give me more comments. Thank you !!!

========================================================== ========================================================== ========================

Author: Cheng
Source: http://rcddup.cnblogs.com
This article was originally published by Cheng and published to the blog Park. You are welcome to repost it, but the author and source must be clearly indicated on the article page. Thank you very much!

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.