MVC series-2. Data Processing-Login

Source: Internet
Author: User
Tags http post custom name connectionstrings

MVC Establish login details steps

0. Create a new folder and plan your code placement

1) Create a new ViewModels folder in the root directory.

The Models folder contains entities that correspond to database tables.

The data that needs to be displayed in the view and the entity model in the Models do not necessarily correspond, so you need a custom data model specifically for view , which we call ViewModel, placed in VIEWMO Dels folder inside.

2) Create a new DAL folder in the root directory.

The DAL places data access related classes. This article puts AccountContext.cs, AccountInitializer.cs

1. Open the last project and create a new two action

This series of article Knowledge points and demo code are based on a previous article, there is a problem can go back to the previous article to find. This time we will create a new user registration/login two pages.

Open Controllersàaccountcontroller.cs, and follow the existing index to add two action, such as.

Note: Add this action to

A. by hand or paste copy,

B. Right-click, insert code snippet (or CTRL k, x) →asp.net mvc4→mvcaction4 (or Mvcpostaction4), as shown in the following photo.

2. Add the action corresponding view

Based on the action added in the previous step, add the relevant View:Login.cshtml, register.cshtml

Add the method described in the previous article, no longer repeat the explanation.

Here again to explain the location of the view of the Convention. Remember the following three words:

1) All views are placed in the View folder

2) Views folder creates a series of subfolders with the same name as the controller

3) The cshtml file with the same name as the action (corresponding view file) is stored in each sub-folder.

3. Completing the Login interface UI

We take login.cshtml as a static HTML page, complete the UI of the login interface, we can understand the cshtml as the original ASPX and HTML mixture: The advantages of using ASPX, convenient and background interaction, using the advantages of HTML, Syntax Concise (htmlhelper).

1) Copy the login interface HTML to bootstrap

http://v3.bootcss.com/css/#forms

2) put it into the login.cshtml body Div.

Right-click Browser View page source and find out more about the VS Browser link scrap code.

We'll disable it.

Open Web. config to add the following code, and then go to the browser to view the source code, you can see the pure HTML.

4. Complete the Registration interface UI ( similar to the login screen, steps slightly)

5. Add EF References

Right-click the project, manage NuGet packages. Select the Entity Framework and click Install.

6. Create a connection string (ConnectionString)

Open the Web. config file and add the following code inside the < Configuration > tags:

<configuration>

<configSections>

<!--for more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468--

<section name= "EntityFramework" type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=6.0.0.0, Culture=neutral, publickeytoken=b77a5c561934e089 "requirePermission=" false "/>

</configSections>

< connectionStrings >

< Add name = " Accountcontext " connectionString = " User id=sa;password=sasa;initial catalog= MVC ;d ata source=.\sqlexpress " ProviderName = " System.Data.SqlClient " />

</ connectionStrings >

。。。。

</configuration>

7. Creating the Model class

Under the Models folder, create a new account class with the following code.

For the conventions and descriptions of the classes above: When EF generates a database, the ID property becomes the primary key. (Convention: EF will default to generate a primary key for ID or Classnameid, MSDN recommends maintaining style consistency, both with ID or Classnameid, we use ID here)

8. Create Database Context

Pre-condition: Install EF

As you can see, the EF Framework implements database operations at the bottom by calling ADO.

Create the class AccountContext.cs under the Dal folder, let him inherit from System.Data.Entity.DbContext, we use this class to complete the function of EF.

Here are three main things to do:

1) Create a dbset for each entity set

In EF, typically an entity set corresponds to a table in the database, one row in the entity table.

2) Specify a connection string

The base ("accountcontext") in the constructor.

By default, like the class name, which is Accountcontext, we explicitly assign it to him.

3) Specify the name of the table in the singular form

Modelbuilder.conventions.remove<pluralizingtablenameconvention> (); By default, a complex form of table is generated, such as sysusers

This line of code requires the introduction of namespaces:

Using System.Data.Entity.ModelConfiguration.Conventions;

NOTE table names use a single plural form to see their own habits, there is no clear rules. Some companies table names are used in the singular, some companies according to the meaning of the table, there are singular and plural.

9. Create initializer, use EF to initialize the database, insert sample data

EF can build databases in a number of ways.

We use the following methods:

The first time you run the program, you create a new database, insert test data, delete the rebuild database when the model changes (and database inconsistency), and insert the test data. Currently in the development phase, without the data loss problem, drop and re-create directly

1) Let's complete this work by creating a new class AccountInitializer.cs.

The seed method uses the database context (that is, accountcontext) that we defined earlier as a parameter to add entities to the database through this context. (That's what we said in front of the bridge function)

As can be seen from the above code, the seed method is for each entity type (we use account):

Create a colletion→ to add to the appropriate DbSet property→ save to the database.

NOTE you do not have to call the SaveChanges method after each entity group and can be called once after all groups have ended. This is done because if there is an error writing the database code, it is easier to locate the wrong location of the code.

2) Modify the Web. config to notify EF to use the initializer class we just wrote.

Locate the EntityFramework configuration section and add the contents of the box.

In the context configuration section, the value of type corresponds to (full description of the context class, assembly)

Databaseinitializer configuration section, the value of type corresponds to (full description of initializer class, assembly)

If you do not want EF to use a context, you can set it to true at the bottom of the box.

10. Connect to the database

Open Controllersàaccountcontroller.cs

Instantiate a database context object

Open the login.cshtml, modify the form, and prepare for the backend to receive the data.

1) First add two properties to the form tag action, method.

For the method in form (the default is get), get is typically used for simple read data operations and post for write data operations.

2) Add the Name property under the INPUT element

The field names of the classes that are set to and models are consistent. Note: The server side needs to use the name to fetch the value.

3) The foreground plus a login status text identification.

First, let's go to AccountController.cs. Create a login with the same name as the action to accept the data submitted by the form.

Note that a [HttpPost] is added to the newly added action to indicate that the action will only accept HTTP POST requests. ASP. NET MVC provides the action Method Selector, HttpPost is one of them.

Typical application scenarios for HttpPost properties:

When it comes to the need to accept client window data, create an action to receive the HTTP GET request for displaying the interface and providing the user with the data;

Another action with the same name applies the [HttpPost] property to receive data from the user and complete the corresponding function.

Open AccountController.cs, modify [HttpPost] Login Action, Query The database for comparison to see if the mailbox and password are correct .

14. Running the program

Open the database and find that the MVC database is new and the sample data is already inserted.

Knowledge Points:

1) The value between the controller and the view is passed--- ViewBag

Controller controllers define:

Viewbag.loginstate = "Success";

View login.cshtml Output:

@ViewBag. loginstate

Note: Loginstate is a custom name that can be arbitrarily, but to match before and after

2) page Jump

Two common methods

Redirecttoaction ("ActionName");

Redirecttoaction ("ActionName", "controllername");

Note that the corresponding controller, action to exist.

3) data query for EF

The EF data query is implemented in LINQ (LINQ to Entities), usually in both expressions and functional styles. It is recommended to use a functional approach , which is relatively simple.

Let's say we've defined the context.

Private Accountcontext db = new Accountcontext ();

[Basic query] query all the Sysuser

var users = db. Accounts; Functional style

[conditional query] Join query criteria

var users = db. Accounts.where (U = u.email = = "[Email protected]"); Functional style

Note that this is the C # notation: "= ="

[Sorting and paging query]

var users = db. Accounts.orderby (U = u.email). Skip (0). Take (5); Functional style

NOTE only sorted to page out

[Aggregate query]

Total number of checks

var num = db. Accounts.count ();

Check Minimum ID

var MiniD = db. Accounts.min (U = u.id);

NOTE aggregate queries can only be queried by a functional type

4) How does the value of the view pass to the controller?

The parameter account field of the login method in the controller matches the name of the input control in the view to get the value.

MVC series-2. Data Processing-Login

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.