has recently been studying ASP.net mvc, read some tutorials, always feel not too deep, so decided to write a series of MVC tutorial, on the one hand to deepen their impressions, on the other hand, to learn MVC students to provide some help, as a reference. This series of tutorials will provide an example of how MVC can be explained from one instance to the next. The
Asp.mvc mode changes the traditional ASP.net webform way, when we use MVC to develop a Web program, we have to discard the traditional webform way of thinking, the traditional WebForm way users drag a button, and then double-click the button, You can write the processing code for the corresponding time in the background. asp.net mvc has only aspx pages and no background aspx.cs pages.
MVC is simply three layers: Controller, model, view.
View is the presentation layer and can be simply interpreted as an ASPX page
model is an entity class that can be simply understood as the entity class for the database table.
Controller is equivalent to a controller between the view and the model layer. The role of controller is to read data from the model layer and display the data on the View page.
This section is about the Web site registration features that are required for each site and see how to do it in MVC mode.
1. Prepare for work.
Development tools: VS2010, sqlserver2005 database
Database user Information table: first create a table in the database to hold user information
--User Information table
CREATE table[dbo].[ UserInfo]
(
[UserName] [varchar] collatechinese_prc_ci_asnotnull,---user name
[userpwd] [varchar] (20) Collatechinese_prc_ci_asnotnull,---Password
[email] [varchar] collatechinese_prc_ci_asnotnull--e-mail
) on[ PRIMARY]
go
ALTER table[dbo].[ Userinfo]addconstraint[pk__userinfo__c9f2845707020f21]primarykeyclustered ([UserName]) on[primary] Go
2. Create model
Then we add the model layer, users in the registration, need to enter the user, password, confirm password, EMAIL, we will establish a corresponding model registration class
<summary>
///Registered user model
///</summary> public
class Registermodel
{
///< Summary>
///username
///</summary>
[DisplayName ("username"]] public
string UserName {get
; set ;
///<summary>
///password
///</summary>
[DisplayName ("password")] public
string Userpwd
{get
;
Set;
}
[DisplayName ("Confirm password")]
public string confirpwd
{get
;
Set;
}
<summary>
///user mailbox
///</summary>
[DisplayName ("Mailbox")] public
string Email
{Get
;
Set;
}
The DisplayName property represents the display name of the field, which can be understood as an alias for the property.
3. Create a View page
The view page is the user-registered page
Right-click on the View folder in the project, and pop up the following window
Here we add a strong type of registration page, to create a strongly typed page, to select the view corresponding model class, such as the red mark above, here we choose Registermodel.
After you add the view page as follows: Strongly typed page inheritance system.web.mvc.viewpage< >
<%@ Page language= "C #" inherits= "system.web.mvc.viewpage<mvclogin.models.registermodel>"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
">
The HTML class above is used to create HTML controls.
Html.BeginForm () is used to create a form control
Html.labelfor used to create label label controls
Html.passwordfor used to create a password text box control
Html.textboxfor used to create a TextBox control
Html.labelfor (M => m.username) This is used to create a label label on the page.
M => M.username is a LAMDA expression that m.username here represents the alias of the property.
This is how the HTML code is generated: <labelfor= "UserName" > Username </label>
4. Create Controller
We create a usercontroller, add a registration method inside, as follows
Publicactionresult Register ()
{return
View ();
}
The name of the view page is the same as the name of the method, when we visit the Register page, the URL jumps to the register () method,
Returns the content to be displayed on the view page by controller the object.
The page effect is as follows:
Where user represents the name of the method in the controller in the Controller,register table, which is the corresponding page.
5.sqlhelper
After the completion of the preparation, we have to register the user, we must have a method to increase the database, we create a sqlhelp class, to perform the operation of the database
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Data.SqlClient;
Using System.Data; Namespace Mvclogin.models {public class SqlHelper {//Database connection string readonly string constr = ' server=.; Uid=sa;pwd=123;database=cztest;
Min Pool size=10; "; String stradd = @ "INSERT into dbo. UserInfo (UserName, Userpwd, Email) VALUES (' {0} ',--Username-varchar ' {1} ',--Userpwd-varchar (20) ' {2
} '--Email-varchar (50)) '; String struserexist = @ "SELECT * FROM dbo.
UserInfo WHERE username= ' {0} ' and userpwd= ' {1} ' '; <summary>///Add user///</summary>///<param name= "model" ></param>///<returns> </returns> public bool AddUser (Registermodel model) {stradd = string. Format (Stradd, model. UserName, model. USERPWD, model.
Email);
SqlConnection con = new SqlConnection (CONSTR); Con.
Open ();
SqlCommand cmd = new SqlCommand (Stradd,con); int o = cmd. ExecuteNonQuery ();
Con.
Close ();
if (o>0) {return true;
return false; ///<summary>///To determine if the user exists///</summary>///<param name= "model" ></param>///<r Eturns></returns> public bool Existuser (Registermodel model) {struserexist = string. Format (struserexist, model. UserName, model.
USERPWD);
SqlConnection con = new SqlConnection (CONSTR); Con.
Open ();
SqlCommand cmd = new SqlCommand (struserexist, con);
SqlDataAdapter ADP = new SqlDataAdapter (cmd);
DataSet ds = new DataSet (); Adp.
Fill (DS); Con.
Close (); if (Ds!=null&&ds. Tables[0].
rows.count>0) {return true;
return false; }
}
}
6. Submit Registration method
When you click the Submit button on the page, you add the user,
The controller Add method is executed, and we add a registration method to the controller class.
<summary>
///Registration submission
///</summary>
///<param name= "model" ></param>
/// <returns></returns>
[HttpPost] public
actionresult Register (Models.registermodel model)
{
bool result = false;
if (!new models.sqlhelper (). Existuser (model))
{result
= new Models.sqlhelper (). AddUser (model);
}
if (result)
{
//Add successfully to the homepage
formsservice.signin (model. UserName, false);
Return redirecttoaction ("index");
}
else
{
//Return to the registration page
viewdata["msg"] = "Add user failed";
return View (model);
}
Some students may ask, there are two register methods in Controll, How to determine which one to call when you click Submit. Note that we have a httppost request in front of this method, which indicates that this method only accepts processing for POST request submissions. By default the method is get, and the request for the submit button belongs to the POST request, and all the registration methods are executed.
7. Create an index page
When the user adds a success, it turns to the index page, and the index page is a strongly typed page. Displays the welcome user's information on the page. We use the form validation of this demo, so we used the FormsAuthentication class.
The final file directory is as follows:
Read this example to explain whether the user registration function is not so difficult to achieve, but we also have to practice, so that in the later learning can be more flexible and skilled use, really become their own things.